Saving instance state helps keep your app's data safe when the screen rotates or the app is temporarily stopped. It prevents losing what the user was doing.
Saving instance state in Android Kotlin
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("key", "value")
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
val value = savedInstanceState.getString("key")
}Use onSaveInstanceState to save data before the activity is destroyed.
Use onRestoreInstanceState or savedInstanceState in onCreate to restore data.
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("score", 42)
}override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
val score = savedInstanceState.getInt("score")
}override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean("isChecked", true)
}This app has a button that increases a number shown on screen. When you rotate the phone, the number stays the same because it is saved and restored using instance state.
import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private var counter = 0 private lateinit var counterText: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) counterText = findViewById(R.id.counterText) val button = findViewById<Button>(R.id.incrementButton) if (savedInstanceState != null) { counter = savedInstanceState.getInt("counter") } counterText.text = counter.toString() button.setOnClickListener { counter++ counterText.text = counter.toString() } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt("counter", counter) } }
Always call super.onSaveInstanceState(outState) to let the system save default state.
Instance state is for small amounts of data like UI state, not for large files or databases.
Data saved in instance state is lost if the app is fully closed or the device restarts.
Saving instance state keeps UI data safe during screen rotations or temporary stops.
Use onSaveInstanceState to save data and onRestoreInstanceState or savedInstanceState in onCreate to restore it.
Good for saving small, temporary data like counters, text input, or checkbox states.