Recipe Saving and Restoring Activity Information

Whenever an activity is about to be killed, the onSaveInstanceState() function is called. Override this to save relevant information that should be retained.When the activity is then recreated, the onRestoreInstanceState() is called. Override this function to retrieve the saved information. This allows for a seamless user experience when an application undergoes lifecycle changes. Note that most UI states do not need to be managed because they are, by default, taken care of by the system.

This function is distinct from onPause(). For example, if another component is launched in front of the activity, the onPause() function is called. Later, if the activity is still paused when the OS needs to reclaim resources, it calls onSaveInstanceState() before killing the activity.

An example of saving and restoring the instance state consisting of a string and a float array is shown in Listing 2.7.

Listing 2.7 Example of onSaveInstanceState() and onRestoreInstanceState()

float[] localFloatArray = {3.14f, 2.718f, 0.577f}; String localUserName = "Euler";

@Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //save the relevant information outState.putString("name", localUserName); outState.putFloatArray("array", localFloatArray);

@Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); //restore the relevant information localUserName = savedInstanceState.getString("name"); localFloatArray = savedInstanceState.getFloatArray("array");

Note that onCreate() also contains the Bundle savedInstanceState. In the case of an activity reinitializing after previously being shut down, the bundle saved in onSaveInstanceState() is also passed to onCreate(). In all cases, the saved bundle is passed to the onRestoreInstanceState() function, so it is more natural to utilize this to restore states.

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook

Post a comment