SavedStateHandle helps you save and restore small pieces of data in your app when the screen rotates or the app is temporarily stopped. It keeps your app's state safe without extra work.
0
0
SavedStateHandle in Android Kotlin
Introduction
You want to keep user input in a form when the phone rotates.
You need to save a counter value during configuration changes.
You want to restore UI state after the app is killed and restarted by the system.
Syntax
Android Kotlin
class MyViewModel(private val state: SavedStateHandle) : ViewModel() { fun saveData(key: String, value: String) { state.set(key, value) } fun getData(key: String): String? { return state.get<String>(key) } }
SavedStateHandle is usually passed to your ViewModel by the system.
You use set(key, value) to save and get(key) to retrieve data.
Examples
Saves a username and then retrieves it.
Android Kotlin
state.set("username", "Alice") val name = state.get<String>("username")
Gets a click count or starts at 0, then increases it by 1.
Android Kotlin
val count = state.get<Int>("clickCount") ?: 0 state.set("clickCount", count + 1)
Sample App
This ViewModel saves a count number. It starts at 0 if no saved value exists. When increment is called, it adds 1 and saves it. The count stays even if the screen rotates.
Android Kotlin
class CounterViewModel(private val state: SavedStateHandle) : ViewModel() { fun getCount(): Int { return state.get<Int>("count") ?: 0 } fun increment() { val current = getCount() state.set("count", current + 1) } } // Usage in Activity (requires SavedStateViewModelFactory): // val factory = SavedStateViewModelFactory(this.application, this) // val viewModel = ViewModelProvider(this, factory).get(CounterViewModel::class.java) // println(viewModel.getCount()) // prints 0 initially // viewModel.increment() // println(viewModel.getCount()) // prints 1 after increment
OutputSuccess
Important Notes
SavedStateHandle works well for small, simple data like strings and numbers.
It is not meant for large data or complex objects.
Use it to improve user experience by keeping UI state consistent.
Summary
SavedStateHandle saves small data automatically during configuration changes.
Use set and get methods to store and retrieve data.
It helps keep your app state safe without extra code for saving/restoring.