Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 104 ยท Activities and the Lifecycle

Configuration Changes and Saved State

Why rotation recreates an Android activity, and how rememberSaveable, SavedStateHandle and onSaveInstanceState keep your state through rotation and process death.

Rotate a phone running a badly written app and the text you typed vanishes, the scroll position resets or a loading screen starts again. This is the most common Android bug for newcomers, and it is not a flaw in the system: it is a deliberate design that you have to understand. When the device configuration changes, Android destroys the activity and creates a new instance so that resources, such as layouts and strings, can be reloaded for the new configuration.

This lesson explains which changes recreate the activity, the three places you can keep state (plain memory, a ViewModel, saved instance state) and when each survives. Real Android code is read-only here because it needs the SDK. The TryIt blocks are stand-ins that simulate recreation with a hand-made Bundle. They are models of the behavior, not the framework. The lifecycle sequence is in The Activity Lifecycle; ViewModel gets its own lesson later.

What counts as a configuration change

A configuration change happens when something about the device setup that affects resources changes while the app runs. The usual causes are:

  • screen orientation (rotation)
  • screen size changes: split-screen, foldable folding, desktop-style window resizing
  • dark or light mode switches
  • language or locale
  • font scale and display size
  • keyboard or input device availability

By default, every one of these destroys the activity (onPause, onStop, onDestroy) and creates a new one (onCreate, onStart, onResume). The new instance is a different object: every field of the old activity is gone. Your app does not become a different app, but your variables do.

You can opt out for specific changes with android:configChanges="orientation|screenSize" in the manifest, so the activity is kept and receives onConfigurationChanged. Avoid this as a general fix. It hides the problem for one case, leaves the others (dark mode, language, process death) broken and means you must update the UI yourself. Design your state so recreation is harmless.

Three places to keep state

Where Survives rotation? Survives process death? Best for
Plain variable or remember No No Throwaway values, such as a running animation
ViewModel Yes No Screen data loaded from a repository, in-flight work
Saved instance state (rememberSaveable, SavedStateHandle) Yes Yes Small user-chosen values: text input, selected tab, scroll position, ids
flowchart TD
    A["Activity running"] -->|"rotation"| B["Old instance destroyed<br/>ViewModel kept"]
    B --> C["New instance created<br/>saved Bundle restored"]
    A -->|"process death"| D["Everything in memory lost"]
    D --> E["New process<br/>only saved Bundle restored"]

Rotation keeps the ViewModel and the Bundle; process death keeps only the Bundle.

Saved instance state in the View world

The original mechanism is onSaveInstanceState. The system calls it before the activity can be destroyed and gives you a Bundle to fill; the same bundle returns to onCreate (and onRestoreInstanceState) in the new instance:

Kotlin
// read-only example: needs the Android SDK
class CounterActivity : ComponentActivity() {
    private var count = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        count = savedInstanceState?.getInt("count") ?: 0
        // ... build the UI using count
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("count", count)
    }
}

The stand-in below plays the system's part. It saves the old activity into a Bundle, "destroys" it and builds a new instance from the bundle. The plain field comes back as 0; the saved one is restored.

Kotlin Simulating recreation with a Bundle (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

rememberSaveable in Compose

In Compose you rarely implement onSaveInstanceState yourself. Use rememberSaveable instead of remember. It stores the value in the saved instance state automatically, so it survives both recreation and process death:

Kotlin
// read-only example: Compose
@Composable
fun SearchBox() {
    var query by rememberSaveable { mutableStateOf("") }
    var expanded by remember { mutableStateOf(false) }   // fine to lose

    TextField(value = query, onValueChange = { query = it })
}

What can it store? Anything that fits in a Bundle: primitives, String, arrays, and classes that are Parcelable or Serializable. For other classes, supply a Saver:

Kotlin
// read-only example
data class Filter(val tag: String, val minRating: Int)

val FilterSaver = listSaver<Filter, Any>(
    save = { listOf(it.tag, it.minRating) },
    restore = { Filter(it[0] as String, it[1] as Int) },
)

@Composable
fun FilterBar() {
    var filter by rememberSaveable(stateSaver = FilterSaver) {
        mutableStateOf(Filter("kotlin", 3))
    }
}

You will meet mutableStateOf, remember and state in depth in State and remember and in rememberSaveable, derivedStateOf and Collections. For now, remember one rule: state the user typed or chose goes in rememberSaveable; state derived from data stays in a ViewModel.

SavedStateHandle in a ViewModel

A ViewModel survives rotation, but not process death. When the screen state includes a user-selected value, such as the search text or the selected category, that value must survive process death too, and the ViewModel gets there through a SavedStateHandle, a key-value map that is backed by the same saved instance state:

Kotlin
// read-only example
class SearchViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
    val query: StateFlow<String> = savedStateHandle.getStateFlow("query", "")

    fun onQueryChange(text: String) {
        savedStateHandle["query"] = text
    }
}

The framework passes the handle to the ViewModel constructor automatically with the default factory. Only put small values in it: ids, strings, flags. The saved instance state is stored by the system process, and large data causes a TransactionTooLargeException or silent trouble. Data that you can reload (a list of notes) belongs in a database, and you save only the id or query that tells you which data to load.

Process death and testing it

When the user leaves the app and the system later needs memory, it kills your process. Everything vanishes except the saved instance state, which the system keeps and hands to the next instance. If the user then returns, they should see the same screen with the same input.

The second stand-in models the three storage levels and plays three events: a rotation, a process death and the user finishing the screen. It shows what each level keeps.

Kotlin What survives what (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

After process death the ViewModel is empty, but the query survived. A well-designed screen restores query from the saved state and reloads the results, so the user notices nothing.

How to test process death

You do not have to wait for the system to run out of memory:

  • In Developer options, turn on Don't keep activities. Leaving an activity destroys it immediately, and returning exercises the restore path.
  • Or, with the app in the background, run adb shell am kill <your.package.name>, then reopen the app from the recents screen. (The command only kills a process that is in the background, which is the realistic case.)

Do this for every screen that holds user input. The bugs it finds are the ones your users report as "the app forgot what I was doing."

A decision guide

  1. Is it a UI-only detail that is fine to lose (an expanded card)? remember.
  2. Did the user type or choose it, and is it small (text, id, tab index, scroll position)? rememberSaveable or SavedStateHandle.
  3. Did you load it from a database or the network? Keep it in a ViewModel (loaded from a repository), and restore by id after process death.
  4. Is it large or long-lived (images, files, user documents)? Persist it to storage: Room, DataStore or files.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to the activity by default when the user rotates the device?

    A configuration change destroys the activity and creates a new instance, so resources can be reloaded. Fields of the old instance are lost unless you save them.
  2. 2. Which storage survives both rotation AND process death?

    Only the saved instance state is kept by the system across process death. A ViewModel survives rotation but its memory is lost when the process is killed.
  3. 3. Why is the android:configChanges manifest attribute a poor general fix for lost state?

    It hides the issue for rotation but dark mode, language changes and process death still recreate or kill the app. Design for recreation instead.
  4. 4. What should you put in a SavedStateHandle?

    Saved state travels through a size-limited system mechanism. Keep it small and reload large data from a database or the network using the saved id or query.
  5. 5. How can you test the process-death path on a device?

    Both options make the system destroy your activity or process while the app is in the background, so reopening it exercises the restore code.

Summary

  • Configuration changes (rotation, dark mode, language, size) destroy and recreate the activity; plain fields are lost.
  • remember and plain variables are lost on recreation; a ViewModel survives it; only saved instance state survives process death.
  • Use rememberSaveable in composables and SavedStateHandle in ViewModels for small user-chosen values.
  • Custom classes need Parcelable, Serializable or a Saver (for example listSaver).
  • Save ids and queries, not large data; reload data from storage.
  • Test process death with Don't keep activities or adb shell am kill.
  • The Android code is read-only; the TryIts are stand-ins modeling a Bundle and the three storage levels.

Next: Runtime Permissions