Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of onSaveInstanceState

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?

like image 369
Zero Avatar asked Jan 27 '26 10:01

Zero


1 Answers

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.

like image 81
wsanville Avatar answered Jan 28 '26 22:01

wsanville



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!