Fragment savedInstanceState is always null when using Navigation Component Fragment savedInstanceState is always null when using Navigation Component android android

Fragment savedInstanceState is always null when using Navigation Component


Fragment will save its state only when activity is recreated (e.g. screen rotation) and changing the fragment doesn't matter. From documentation:

There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.

Source

Saving custom state:

Put this method inside fragment:

override fun onSaveInstanceState(outState: Bundle) {    outState.putString("text", "some value")    super.onSaveInstanceState(outState)}

And read the value, for example, inside onViewCreated:

val text = savedInstanceState?.getString("text")

You will receive desired value after screen rotation / phone language change or other config changes - when activity (and fragment) is being recreated.


Check this Blog, http://www.androiddevelopment.co.in/2019/05/how-to-save-android-activity-state.html, This Blog explain how to save activity state when the activity is destroyed.

For example, If you change the language of your phone while the activity was running (and so different resources from your project need to be loaded). Another very common scenario is when you rotate your phone to the side so that the activity is recreated and displayed in landscape. You can use this technique to store instance values for your application (selections, unsaved text, etc.).