Saving and Restoring Activity Instance State Using the Lifecycle Handlers

Activities offer the onSaveInstanceState handler to persist data associated with UI state across sessions. It’s designed specifically to persist UI state should an Activity be terminated by the run time, either in an effort to free resources for foreground applications or to accommodate restarts caused by hardware configuration changes

If an Activity is closed by the user (by pressing the Back button), or programmatically with a call to finish, the instance state bundle will not be passed in to onCreate or onRestoreInstanceState when the Activity is next created. Data that should be persisted across user sessions should be stored using 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 put methods as shown for Shared Preferences, before passing the modified Bundle into the superclass’s handler:

private static final String TEXTVIEW_STATE_KEY = “TEXTVIEW_STATE_KEY”;
public void onSaveInstanceState(Bundle saveInstanceState) {
 // Retrieve the View
 TextView myTextView = (TextView)findViewById(;
 // Save its state

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 lifecycles 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.

public void onCreate(Bundle savedInstanceState) {
 TextView myTextView = (TextView)findViewById(;
 String text = “”;
 if (savedInstanceState != null && 
 text = savedInstanceState.getString(TEXTVIEW_STATE_KEY);

Leave a Comment