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).
onSaveInstanceStateis called before activity destruction, such as during screen rotation.- Data restoration occurs in
onCreateoronRestoreInstanceState. - Use
Bundleto 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)
}