Monday, September 30, 2013

Android Tutorial: Recreating an Activity

Probably I really should read this tutorial much earlier, while it's never too late to learn. The key knowledge in this tutorial confused me for a while.

  • By default, the system uses the Bundle instance state to save information about each View object in your activity layout (such as the text value entered into an EditText object). So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables that track the user's progress in the activity.
  • To save additional data about the activity state, you must override the onSaveInstanceState() callback method. The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate() methods.

To Save your Activity State, such as the text in EditText, the scroll position of ListView, etc.
  • Call onSaveInstanceState(), in this function, save state information like saving Preference for the App. The super function is call at the end of this override callback function. This function is called precisely right after onPause() being called. I have this confirmed with my customized demo code from tutorial.
To Restore your Activity State, two ways can be used:
  1. In onCreate() function, savedInstanceState has saved state information, but need to check if it's null or not before fetch any information from it.
  2. Call onRestoreInstanceState(), in this function, doesn't need to check the nullity, because this function would not be called unless there exists saved state information already. One thing to remember for using this function, this function is called between onStart() and onResume(). The super function is called at the beginning of this override callback function.

No comments :

Post a Comment