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”;
@Override
public void onSaveInstanceState(Bundle saveInstanceState) {
 // Retrieve the View
 TextView myTextView = (TextView)findViewById(R.id.myTextView);
 // 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 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.

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 TextView myTextView = (TextView)findViewById(R.id.myTextView);
 String text = “”;
 if (savedInstanceState != null && 
 savedInstanceState.containsKey(TEXTVIEW_STATE_KEY))
 text = savedInstanceState.getString(TEXTVIEW_STATE_KEY);
 myTextView.setText(text);
}

Leave a Comment