I've been trying to build a task list in Android, and I want it to remember what is in the list even if the application is closed. I've been trying to do this using onSaveInstanceState as follows:
public class Main extends Activity implements OnClickListener, OnKeyListener {
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
...
if (savedInstanceState != null) {
ToDo = savedInstanceState.getStringArrayList("MyArrayList");
AA.notifyDataSetChanged();
} else {
ToDo = new ArrayList<String>(); // Initiate ToDo
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putStringArrayList("MyArrayList", ToDo);
}
// ...To-Do implementation follows
}
But this doesn't work, so I started reading about onSaveInstanceState and if I understand it right, then you actually cannot save data between sessions with it. So how can you do it then?
Check out the Android documentation about Data Storage for your options for persisting data. You can use Shared Preferences, a SQLite database, files in a private internal directory, or files on the SD card (if available).
Basically, onSaveInstanceState is used for the scenario where Android kills off your activity to reclaim memory. In that scenario, the OS will keep a record of your activity's presence, in case the user returns to it, and it will then pass the Bundle from onSaveInstanceState to your onCreate method. It's not meant to be used to general purpose storage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With