Sobes.tech
Junior — Middle

How is data preservation ensured when changing screen orientation in mobile applications?

sobes.tech AI

Answer from AI

When the screen orientation changes in Android, the Activity is recreated, which leads to the loss of the current state. The following methods are used to save data:

  • onSaveInstanceState(Bundle outState) — a method where necessary data can be saved into the Bundle object before the Activity is destroyed.
  • onRestoreInstanceState(Bundle savedInstanceState) or retrieving data from savedInstanceState in onCreate to restore the state.
  • Using ViewModel from Android architecture components, which retains data during Activity recreation.
  • Saving data in Persistent Storage (e.g., SharedPreferences or a database) for long-term storage.

Example of saving a counter state:

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

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    if (savedInstanceState != null) {
        currentCounter = savedInstanceState.getInt("counter")
    }
}