Intro to Android

Instance State

When you want to save the state of view components or other things that are not stored in more permanent storage, you would use the save and restore instance state.

Let's say you're building an application that searches for your favorite city's cuisine and you have an EditText that allows them to enter a search term. If you rotate the device, the activity is destroyed and recreated thereby using the term that they have already entered. It's annoying to have to reenter that term when you just did! You can preserve the user experience by storing that value for retrieval when the view is restored.

In addition to recreating the activity on rotation, this could also be invoked if the system kills your activity to free up space and later brings it back to the foreground. This could happen if you background the app for a phone call and then check your email, Twitter, and Facebook then go back into your city search app.

Basically, there's no guarantees in the Android world of when your app will be killed or restored, so you want to avoid user surprise as much as possible.

onSaveInstanceState()

This is where you'd save simple pieces of data, a String for a EditText, a value for a slider, etc. You have several built in types that you can store, but if you want more options, you can create a class that implements Parcelable and store your data structures to support your view.

Restore

Tied to the activity and fragment states. Can get access to the instance state in onCreate() of the activity. In fragments, you retrieve this data in onActivityCreated().