What is the savedInstanceState Bundle?
The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity. Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle. If there is no available instance data, the savedInstanceState will be null. For example, the savedInstanceState will always be null the first time an Activity is started, but may be non-null if an Activity is destroyed during rotation.
When do I save things to the Bundle?
All activities have an onSaveInstanceState method that can be overridden. When this method is called, any state-related data should be placed into the outState Bundle. This method is called when an Activity is being backgrounded (either after onPause() or onStop(), depending on different factors).
What should be saved?
The savedInstanceState Bundle should only save information directly related to the current Activity state. Examples of this include:
- User selections – A user selects a tab. In onSaveInstanceState the tab selection gets added to the outState Bundle. During the next onCreate, the selected tab will be available within the Bundle, and the Activity should default to having that tab selected.
- Scroll view positions – A user scrolls half way through a ScrollView. The current position of the ScrollView should be saved in onSaveInstanceState then restored when the Activity is re-created.
- User-submitted data – If a user writes their username into a text box, they would expect the username to still be present when the Activity is resumed.
What should not be saved?
In general (with few exceptions), the following kinds of data should never be saved into the Bundle:
- Database data
- Anything downloaded from the web (feed data)
- Models (the data kind, not the people kind)
Rather than attempting to save and recover this information from the Bundle on rotation, the application should have caching and/or database systems set up that are built to deal specifically with these kinds of information.
When is the savedInstanceState useful?
There is one situation where using the savedInstanceState is almost mandatory: when the Activity gets destroyed during rotation. One way that Android handles rotation is to completely destroy and then re-create the current Activity. When the Activity is being destroyed, any state related information that is saved in onSaveInstanceState will be available when the Activity comes back online.
Another situation is when your Activity gets backgrounded. When an Activity is in a backgrounded state (either after onPause or onStop) it can be destroyed at any time with no notice. In the event that the OS kills your Activity without killing your Application, the OS will first save your outState Bundle so you can later return to your previous state.
About the AuthorMore Content by James Halpern