java – Retaining ListView items after application reload

Question:

There is an application in which, when a button is clicked, elements of a ListView are created and added. When you restart the application, they disappear. I guess that you need to use the database, and when creating an element, add it to the database, and in the OnCreate method put the creation of the ListView list from the elements in the database (correct if I'm wrong). The question is: is it possible to save the list after restarting the application WITHOUT USING the database, because there will be a maximum of 10-15 elements in the list (this is the ceiling). B

Answer:

The Activity has an onSaveInstanceState that fires when it closes. Override it to save the data from the ListView :

public void onSaveInstanceState(Bundle savedState) {

    super.onSaveInstanceState(savedState);

    // здесь берём данные из адаптера
    // если у вас ArrayAdapter, то будет так
    String[] values = mAdapter.getValues(); 
    savedState.putStringArray("myKey", values);

}

And then in onCreate get:

public void onCreate (Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        String[] values = savedInstanceState.getStringArray("myKey");
        if (values != null) {
           mAdaptor = new MyAdaptor(values);
        }
    }

    [...]

}
Scroll to Top