Save State Information during Changes in Configuration

Description

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//ww w .ja  v  a2 s .c  o  m
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// w  w w  . ja v a  2s  . c o m
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//from www  .  j  av  a2s.co m
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/* ww w.j  a  va2s.c om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Log.d("StateInfo", "onCreate");
    String str = (String) getLastNonConfigurationInstance();
}




















Home »
  Android »
    Android Basics »




Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS