Sobes.tech
Junior — Middle

How to ensure the preservation of the current system state when changing configuration?

sobes.tech AI

Answer from AI

In Android, to preserve the current system state when the configuration changes (for example, screen rotation), the mechanism of saving the state of an Activity or Fragment is used.

Main methods:

  1. onSaveInstanceState(Bundle outState) — a method where you can save necessary data into a Bundle object. This data will be available when recreating the Activity in the onCreate or onRestoreInstanceState methods.

  2. ViewModel — a component from Android's architecture components that retains data during configuration changes and is not recreated along with the Activity.

  3. Saving UI component states — many standard widgets automatically save their state if they have a unique identifier.

Example of saving a counter state:

class MainActivity : AppCompatActivity() {
    private var counter = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        counter = savedInstanceState?.getInt("counter_key") ?: 0
        // update UI with current counter value
    }

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

Thus, when the configuration changes, data is not lost, and the user will see the same interface and state.