1

There is a lot of noise surrounding this subject on SO and Google, so bear with me.

When performing Fragment to Fragment navigation, you see this lifecycle:

Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView

Fragment2: onCreateView
Fragment2: onStart
Fragment2: onResume

(You can see this in this picture stolen from here) enter image description here

There is no call to a Fragment.onSaveInstanceState as the Fragment instance is still alive - only it's view has been destroyed.

What mechanism therefore is saving the View's state and restoring it, and how?

Graeme
  • 25,714
  • 24
  • 124
  • 186

1 Answers1

-1

onSaveInstanceState will be called according to documentation:

This method will occur after onStop() for applications targeting platforms starting with Build.VERSION_CODES.P. For applications targeting earlier platform versions this method will occur before onStop() and there are no guarantees about whether it will occur before or after onPause().

In onSaveInstanceState you can put all the data you want to persist in the bundle

override fun onSaveInstanceState(outState: Bundle) {
// put data you want to persist to outState
super.onSaveInstanceState(outState)

}

And then in onCreate you can check if you need to restore your persisted data:

  override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
  // activity created for the first time
} else {
  // activity re-created, restore data from savedInstanceState
}

}

You can also read more about it here: https://developer.android.com/topic/libraries/architecture/saving-states

  • Thanks for your answer, but Fragment to Fragment navigation doesn't involved onSaveInstanceState() - There is a lot of noise around this topic because of the assumption it uses the same mechanism as Activity to Activity (or configuration change) – Graeme May 21 '20 at 18:48
  • I've updated the question to highlight the situation I'm asking about – Graeme May 21 '20 at 18:50
  • If you want to persist Fragment's data, while navigating, you should use `ViewModel`. It is always created in association with a scope (a fragment or an activity) and will be retained as long as the scope is alive. E.g. if it is a `Fragment`, until its `onDestroy` was called and there was **NO configuration change** (device rotation). If you want to persist data across multiple Fragments, have a common activity scoped ViewModel and observe it's `LiveData` in those Fragments, who need it. Let me know, if this is what you want, I can update my answer with some code examples. – – Jokubas Trinkunas May 22 '20 at 17:09