Android How to - Save State Information during Changes in Configuration








When an activity is killed, it will fire one or both of the following two methods:

  • onPause() is always fired whenever an activity is killed or pushed into the background.
  • onSaveInstanceState() is also fired whenever an activity is about to be killed or put into the background. onSaveInstanceState() method is not fired when an activity is being unloaded from the stack, because there is no need to restore its state later.

To preserve the state of an activity, you could always implement the onPause() method.

To preserve the state of an activity so that it can be restored later when the activity is recreated, a much simpler way is to implement the onSaveInstanceState() method, as it provides a Bundle object as an argument so that you can use it to save your activity's state.





Example

The following code shows that you can save the string ID into the Bundle object during the onSaveInstanceState() method:

@Override
public void onSaveInstanceState(Bundle outState) {
    //save whatever you need to persist
    outState.putString("ID", "1234567890");
    super.onSaveInstanceState(outState);
}

When an activity is recreated, the onCreate() method is first called, followed by the onRestoreInstanceState() method.

@ Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    //retrieve the information persisted earlier
    String ID = savedInstanceState.getString("ID");
}

Bundle object only support basic data types.





Example 2

onRetainNonConfigurationInstance() method is fired when an activity is about to be destroyed due to a configuration change.

You can save your current data by returning it in this method, like this:

@Override
public Object onRetainNonConfigurationInstance() {
    //save whatever you want here; it takes in an Object type
    return ("Some text to preserve");
}

This method returns an Object type, which allows you to return nearly any data type.

To extract the saved data, you can extract it in the onCreate() method, using the getLastNonConfigurationInstance() method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Log.d("StateInfo", "onCreate");
    String str = (String) getLastNonConfigurationInstance();
}