Saving and Restoring Instance State

To save Activity instance variables, Android offers a specialized variation of Shared Preferences.

By overriding an Activity's onSaveInstanceState event handler, you can use its Bundle parameter to save UI instance values. Store values using the same get and put methods as shown for Shared Preferences, before passing the modified Bundle into the superclass's handler, as shown in Listing 6-6.

LISTING 6-6: Saving Activity instance state

Available for download on private static final String TEXTVIEW_STATE_KEY = "TEXTVIEW_STATE_KEY";

©Override public void onSaveInstanceState(Bundle saveInstanceState) { // Retrieve the View

TextView myTextView = (TextView)findViewById(; // Save its state saveInstanceState.putString(TEXTVIEW_STATE_KEY, myTextView.getText().toString()); super.onSaveInstanceState(saveInstanceState);

This handler will be triggered whenever an Activity completes its active lifecycle, but only when it's not being explicitly finished (with a call to finish). As a result, it's used to ensure a consistent Activity state between active life cycles of a single user session.

The saved Bundle is passed in to the onRestoreInstanceState and onCreate methods if the application is forced to restart during a session. Listing 6-7 shows how to extract values from the Bundle and use them to update the Activity instance state.

LISTING 6-7: Restoring Activity instance state

Available for download on @Override public void onCreate(Bundle savedlnstanceState) super.onCreate(savedlnstanceState); setContentView(R.layout.main);

TextView myTextView = (TextView)findViewByld(; String text = "";

if (savedlnstanceState != null && savedInstanceState.containsKey(TEXTVIEW_STATE_KEY))

text = savedInstanceState.getString(TEXTVIEW_STATE_KEY);


It's important to remember that onSavelnstanceState is called only when an Activity becomes inactive, and not when it is being closed by a call to finish or by the user's pressing the back button.

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


  • Lennon
    How to save and restore activity state in android?
    7 years ago

Post a comment