How to maintain state values when Android changes configuration

Oscar de la Hera Gomez
Three flowers that represent Kotlin, Android and Android Studio side by side. Beneath them sits the text “Persistent States.”

A step by step guide on keeping state values within an Activity during configuration changes such as a change in screen orientation, language or input devices.

What is happening ?

Tutorial

The following tutorial demonstrates how to maintain the experience state state value of the MainActivity in our Open Source project. This makes sure that the app shows the user the same screen as they were on after an orientation change.

If you wish to test it, download the project through the repository linked below.

Step One: Create the Key(s)

A screenshot of Android Studio showing the MainActivityKeys.kt file that we created along with the ExperienceState key.

We recommend creating a file per activity in your project and creating a string that serves as a type-checked constant for saving and retrieving states.

Step Two: Save the State(s)

A screenshot of Android Studio showing how to save states during configuration changes. Code available below.

In the relevant activity, save the state(s) using the key(s) created in Step One.

Step Three: Restore the State(s)

A screenshot of Android Studio showing how to restore states during configuration changes. Code available below.

In the same activity, restore the state(s) using the key(s) created in Step One.

Step Four: Test

A screenshot of Android Studio showing the Menu screen of our open source project in Landscape demonstrating that the state was saved and restored succesfully.

Run the app and confirm that the states persist when the Android configuration changes.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details