Sobes.tech
Junior — Middle

What should be considered when saving the application state using the onSaveInstanceState method?

sobes.tech AI

Answer from AI

When using onSaveInstanceState, it is important to remember:

  • Save only small and necessary data, such as UI state (text in fields, selected items).
  • Do not save large objects or data that can be restored differently (e.g., from database or network).
  • onSaveInstanceState is called before activity destruction, such as during screen rotation.
  • Data restoration occurs in onCreate or onRestoreInstanceState.
  • Use Bundle to save data; primitive types, Serializable, Parcelable are supported.

Example of saving text from EditText:

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putString("input_text", editText.text.toString())
}

override fun onRestoreInstanceState(savedInstanceState: Bundle) {
    super.onRestoreInstanceState(savedInstanceState)
    val text = savedInstanceState.getString("input_text")
    editText.setText(text)
}
What should be considered when saving the application… - sobes.tech