Free Android app covering all aspects of addiction, including prevention and treatment

Saving the Activity’s Instance State: A Tutorial

  • Written by  Clive

How to save your Activity’s Instance State

What is Instance State?

ConfigChange iconThe data that is saved by the system to restore the previous state of an activity is called the Instance State. This data is saved as a collection of key/value pairs in a Bundle object.

For more on Bundles, see Passing data between activities.

The Activity loses all information about its state when it is destroyed.

The Instance State data stored in the Bundle object is used to restore the activity to its previous state when the activity is recreated.

Our Tutorial app

What we’ll learn:

  • What is saved by the default implementation of onSaveInstanceState
  • How to use onSaveInstanceState to save additional information
  • How to use Shared Preferences to save more important information

Our Tutorial app summary

Running the app shows a screen with three edit text fields, two text fields and two buttons.

Screenshot of saving activity's instance state

The counters are set to 0 and the edit text fields still need to be filled in

Pressing the left, Text button fills in the edit text fields. It also resets the two counters (the values of which are displayed in the two text fields) to zero.

Pressing the right, Counter button increases the counter which is then displayed in both text fields.

Second screenshot of saving activity's instance state

Pressing the Text button fills in the edit text fields

Changing the orientation

Changing the orientation of the device destroys and then recreates the activity.

In order to restore it to its original state that original state has to have been saved somewhere.

Let the system do it: The default implementation of onSaveInstanceState

If the activity completes its active lifecycle when it is destroyed then the system will automatically save its Instance State in a Bundle object. See The Activity Lifecycle article.

This bundle contains information about each view object in the activity’s layout. These view objects must have a unique ID if they are to be restored.

Some information, like member variables, is not saved.

Note that in our tutorial app, the text values entered into the edit text fields are saved by default. The countText variable is not saved by default. We need to override onSaveInstanceState to save the countText variable.

The bundle is then used in onCreate to rebuild the activity after the orientation change.

You do it: Overriding onSaveInstanceState to save additional information

Sometimes you may need to save additional information that is not automatically saved when the activity is destroyed. You can do this by overriding the onSaveInstanceState.

In our app, we need to override the onSaveInstanceState method to save our countText variable. It is then restored when the activity is recreated.

Here’s our code:

Saving Activity Instance State onSaveInstanceState

Note the following:

  • textView – we get an instance of the text view where we display the countText value
  • countText – a string value of the prefCountText integer. Each time the button is pressed, this value is displayed in the text view
  • getText() – we use getText() to get the value displayed in the text view (it’s the prefCountText value which is an integer)
  • toString() – we convert the integer value to a String
  • putString() – we put this value into the saveInstanceState bundle as a key/value pair
  • SAVED_STATE_COUNTER_KEY – we use this as the key for the countText value. We’ll use it later to extract the value out of the bundle
  • Super.onSaveInstanceState() – call the superclass so that it saves the view hierarchy

Try this at home

Comment out the onSaveInstanceState method, run the app. Press the Counter button to increase the counter and display it. Change the orientation of the device.

You’ll see that the text view (yellow square) displays but it’s empty. The TextView view is saved by default but the countText value is not.

Saving the activity's instance state

Un-comment the onSaveInstanceState method and run the app again. Press the Counter button a few times. Change the orientation and notice that this time the counter value is displayed correctly. Its value has been saved and restored when the activity is recreated.

Saving your Swiss bank account number: Saving important additional information using Shared Preferences

onSaveInstanceState is sometimes not implemented so you cannot guarantee that it will always save your data.

You can use Shared Preferences to save important additional information. It’s advisable to do this in onPause as it is always called so you will be assured that the information will be saved.

For more on SharedPreferences, see Using Android’s SharedPreferences to save persistent data: a practical example and tutorial.

Here’s our code:

Saving the activity's instance state onPause

Note the following:

  • getPreferences() – gets a SharedPreferences object private to this activity
  • MODE_PRIVATE – makes the preference file private to this application
  • editor – the editor allows us to modify the SharedPreferences  object
  • putInt() – we put the prefCountText value into the SharedPreferences object along with its key, counter
  • commit() – commits the key/value pair to the preference object

Try this at home

Comment out the line containing commit in the onPause method. This ensures that the prefCountText value is not saved as a Shared Preference.

Run the app and press the Counter button repeatedly. Notice that the value in both text views increases. Change the orientation of the device. Notice that the left text view now displays 0 (or whatever value is contained in the Shared Preference file) while the value in the yellow box reflects the value that was displayed before the orientation change. (Make sure that the onSaveInstanceState method is not commented out).

Saving the activity's instance state

The prefCountText value that is displayed in the left text view is reset to whatever the value is in the Shared Preference file. The countText value that is displayed in the yellow box has been saved in the onSaveInstanceState method and used when the activity was recreated

Bring back the past: Restoring the Activity’s Instance State

You can restore the instance state in either the onCreate or the onRestoreInstanceState methods.

Do it in onCreate

Restoring the Activity State: The System does it for you, the default implementation of onSaveInstanceState

If you’re restoring the Activity’s Instance State using the default implementation then you don’t have to do anything.

In other words, you have not included the onSaveInstanceState method. And you are not interested in saving any additional information. The system will take care of everything for you and restore the Activity’s state.

Restoring the Activity State: You do it, overriding onSaveInstanceState

If you’ve overridden the onSaveInstanceState method to save additional information then this is how you access that additional information in order to restore the activity.

The first thing that you need to do is to include an if statement to check whether there is a Bundle object. You will get an error if you try and get the string out of a non-existent bundle (which is the case when the app runs for the first time).

If there is a bundle then you can get the values out of it using the get<type> methods.

This is how we did it. Here’s our code:

Restoring the instance state in onCreate

Note the following:

  • Null – we check if the saved bundle exists and if it contains the key we’re looking for
  • SAVED_STATE_COUNTER_KEY - we save the values in the bundle as key/value pairs. This is the key that we used for the countText value
  • containsKey() –we use containsKey to check if the key we’re looking for is contained in the bundle
  • getString() – we get the value matching the key out of the bundle and assign it to countText
  • setText() – we set the text view to display the countText value

Do it in onRestoreInstanceState

You can also choose to restore the activity’s state by implementing the onRestoreInstanceState method.

You don’t have to check whether a bundle exists as onRestoreInstanceState is only called if there is a saved instance state bundle.

It restores the default instance state values as well as any additional information saved in the bundle as key/value pairs.

Here’s our code:

Saving the activity's instance state onRestoreInstanceState

Note the following:

  • make sure that you call the superclass first so that it can restore the view hierarchy
  • SAVED_STATE_COUNTER_KEY - we save the values in the bundle as key/value pairs. This is the key that we used for the countText value
  • getString() – we get the value matching the key out of the bundle and assign it to countText
  • setText() – we set the text view to display the countText value

If you prefer: Restoring the SharedPreferences values in onResume()

onResume is always called when the activity becomes active. This is where you can get your saved data out of the Shared Preferences file.

Here’s our code showing how we did it:

Saving the activity's instance state onResume

Note the following:

  • getPreferences() – gets a SharedPreferences object private to this activity
  • MODE_PRIVATE – makes the preference file private to this application
  • getInt() - we get the prefCountText value out of the SharedPreferences object by passing  getInt() two parameters:
    • its key, counter
    • -1 – the default value to use if there is no matching value for the key
  • setText() – we set the left text view to display the prefCountText value that we have just retrieved from the Shared Preferences file

You may also be interested in this article, Persisting the Activity's Instance State and this tutorial, Fragments, configuration changes and retaining objects.

I hope that you have found this tutorial helpful.

Please consider subscribing to our notification email. We’ll send you one email on Friday with links to our latest tutorials. That way you won’t miss out. If we didn’t publish any then we won’t send any email. No spam. 

This tutorial was created using Android Studio. You can download the project files here Download icon

Are you using Eclipse or another IDE? Here's how you can use this project's Android Studio files.