How to keep text from a TextView after the App close

1
Well, I'm new to Android, but I'd like to know how I can keep / store the information in a TextView, so it will not be deleted when I close the application.

     public class Activity extends AppCompatActivity {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss");
        String strDate = sdf.format(c.getTime());

                @Override
                  protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity);
                  EscreverData();}

               private void EscreverData(){
                  TextView datas = (TextView) findViewById(R.id.datas);
                  datas.append(strDate);}}

Basically what I intend is, when this activity starts, get the date and time and display this information in the TextView. However, I liked it to continue to store the old dates and not delete them every time the activity is started again. I've tried searching a bit and I think a good solution could be SharedPreferences but I do not know how to use it. Thanks if you can help me

    
asked by anonymous 11.08.2017 / 19:00

1 answer

3

A simple way to persist data is to use SharedPreference as shown in the documentation on How to save key-value sets . Here is an example of how to save, assuming you have any variable with some text:

String value = "Um texto qualquer";
SharedPreferences sharedpreferences = getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("str_textview", value);
editor.commit();

To redeem:

SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
String text = pref.getString("str_textview", null);
meuTextView.setText(text );

See Save Value on SharedPreference for more details.

In this way, at any time of your application, you can regroup the value that was saved in a given key. See here at Persistence levels of data in Android applications other approaches.

No Kotlin would look like this:

val value = "Um texto qualquer"
val sharedpreferences = context.getSharedPreferences("pref", Context.MODE_PRIVATE)
val editor = sharedpreferences.edit()
editor.putString("str_textview", value)
editor.commit()

To redeem:

val pref = context.getSharedPreferences("pref", MODE_PRIVATE)
val text = pref.getString("str_textview", null)
myTextView.setText(text)
    
11.08.2017 / 19:09