Tip about the Handling Configuration Changes in a Relationship between Activities and Fragments

Tássio Auad
Younger Auad
Published in
2 min readApr 20, 2016
by Philip Barlow / from beautifuldecay.com

I’ve sometimes posted about configuration changes, screen rotations and etc, but now I will write about a mistake that I made at the beginning when this handling involves Activity and Fragments.

Let’s take as example a simple Activity with a Fragment. We have to handle the configuration changes of the activity and the fragment and this relationship brings some extra details. That’s our Activity:

There is any code where the state is saved and configuration changes is handle in this Activity because I want to focus on Fragment. But you can imagine it happening even that I haven’t done. And that’s our Fragment:

Let’s analyse when the Activity starts the Fragment. Inside the Fragment, the savedInstanceState param is obviously null, because the method onSaveInstanceState() has not yet been called and we don’t have a bundle with all of the states saved. So, the Fragment will deal with the Arguments received from the Activity, calling the method getArguments(). Inside the Bundle of Arguments we have the ID of the MyObject and we will use it to search the specific MyObject.

If the screen is rotated, this Fragment will save the MyObject instance because we don’t want to search it again. After it, the Fragment will be destroyed and recreated. At this time, the savedInstanceState is not null and the Fragment will deal with it, pulling out the saved MyObject instance of it.

But we have a problem. When the Activity is destroyed and recreated, the onCreate() method will replace that Fragment for a new instance and all of our work of save the state keeping the MyObject instance saved will go in vain!

So, we have to do some modifications on our Activity to avoid this situation. The tip is: We will check if the Bundle received in the method onCreate of the Activity is null. If it is null, is because the Activity is being created for the first time. If it is not null, mean that the Activity was destroyed and is been recreated.

OR we can do this check using the tag to reference our fragment on the FragmentManager:

Now it’s respecting the Fragment life cycle. Take care about it. Even if you handle the configuration changes in the Activity and in the Fragment, you can kill the lifecycle with some mistakes like that.

--

--

Tássio Auad
Younger Auad

Christian, Mobile Developer, Tea Drinker, Caffeine Dependent Life-Form