Saving Fragment State on Configuration Change

Fragment Component
Fragment lifecycle

What I needed :
As you know (if not, please read the prerequisite first), the Fragment lifecycle is highly tied to the activity lifecycle. That said, my need was simply to retain some state of my Fragment and restore it later on after a recreation. A typical scenario is when user rotates screen.
To do so, one needs to override onSaveInstanceState method of the Fragment and save any value into a Bundle, as follow :

The saved Bundle could be retrieved during either onCreate(), onCreateView(), onViewCreated(), onActivityCreated() or onViewStateRestored() callbacks.

What was the problem ?
In my case, the saved bundle was always null in any of the callbacks listed above, although I properly called onSaveInstanceState().

How to solve it ?
Firstly, my Activity’s layout looked like this :

What was missing here is an android:id field within my fragment so Android could recognize the stored Fragment! We simply correct the layout as follow :

As described in the documentation,

Each fragment requires a unique identifier that the system can use to restore the fragment if the activity is restarted (and which you can use to capture the fragment to perform transactions, such as remove it). There are three ways to provide an ID for a fragment:
Supply the android:id attribute with a unique ID.
Supply the android:tag attribute with a unique string.
If you provide neither of the previous two, the system uses the ID of the container view.

In a word, always feed your fragment with an identifier !

Une réflexion au sujet de « Saving Fragment State on Configuration Change »

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *