How to store the last 5 opening dates of an Android activity in a list

Asked

Viewed 37 times

0

 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);}}

Here’s my code, but, as you can see, the only thing it does is it presents, in Textview, the date of entry, of that moment, into activity. What I really wanted was to present in Textview the last 5 dates of entry into the activity, without disappearing, when I left the application, that is, store them in a list... If anyone can help me, I’d appreciate it

  • 1

    Use Sharedpreferences: https://developer.android.com/training/basics/data-storage/shared-preferences.html?hl=pt-br

1 answer

0


public class Activity extends AppCompatActivity {
        public static final String PREFS_NAME = "Preferences";
        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);
        TextView datas = (TextView) findViewById(R.id.datas);
        datas.setMaxLines(5);
//Restaura as preferencias gravadas
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_APPEND);
        String a = settings.getString("PrefUsuario", "");
        datas.append(strDate + "\n" + a);}

/**Chamado quando a Activity é encerrada.*/
@Override
protected void onStop(){
        super.onStop();
        TextView datas = (TextView) findViewById(R.id.datas);
        String a = datas.getText().toString();
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_APPEND);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("PrefUsuario", a);
//Confirma a gravação dos dados
        editor.commit();}}

Here is, I think, the solution to my own question - Through Sharedpreferences

Browser other questions tagged

You are not signed in. Login or sign up in order to post.