onSaveInstanceState()

onSaveInstanceState(): This callback is meant to retain a small amount of UI related data in two situations:

  • The app’s process is stopped when it’s in the background due to memory constraints.
  • Configuration changes.

onSaveInstanceState() is called in situations in which the activity is stopped, but not finished, by the system. It is not called when the user explicitly closes the activity or in other cases when finish() is called.

The default implementation of this method saves transient information about the state of the activity’s view hierarchy, such as the text in an EditText widget or the scroll position of a ListView widget.

onSaveInstanceState() is not designed to store large amounts of data, such as bitmaps.onSaveInstanceState() is designed to store data that is small, related to the UI and not complicated to serialize or deserialize. Serialization can consume lots of memory if the objects being serialized are complicated. Because this process happens on the main thread during a configuration change, it needs to be fast so that you don’t drop frames and cause visual stutter.

Use a ViewModel to maintain state due to configuration changes. Use onSaveInstanceState() to save UI information when an activity is paused but not destroyed.

results matching ""

    No results matching ""