Sunday, December 08, 2013

Android Tip - Saving Instance State

One of the characteristics of an activity that it is automatically destroyed and recreated whenever there is a change in device orientation. As such, it is important that you take note of this so that you don’t lose any data when the user accidentally rotates the device.


When an activity is rotated, the activity will fire the onSaveInstanceState() method before the activity is destroyed:

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //---save whatever you need to persist—
        outState.putString("str", "This is a string!");
    }

You can make use of the Bundle object to save the state of your activity.

Do not confuse the onSaveInstanceState() method with the onPause() and onStop() methods, as:
·       The onPause() and onStop() methods are always called when an activity is sent to the background or is being destroyed
·       When an activity is being destroyed, the onSaveInstanceState() method will not be called; it will however be called when the activity is sent to the background
·       The onSaveInstanceState() method will be called when it is being killed by the OS due to a memory crunch

When the activity is created, you can use the onRestoreInstanceState() method to restore the previous saved state of the activity:  

    @Override
    public void onRestoreInstanceState(
    Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        //---retrieve the information persisted earlier---
        String s = savedInstanceState.getString("str");
        Toast.makeText(this, s, Toast.LENGTH_LONG).show();
    }


While usually you can also use the onCreate() method to restore the activity state, the onRestoreInstanceState() method is another method for you to restore the activity state.

No comments: