In the fragment doc, in one of the example, they check for savedInstanceState == null
when adding a fragment:
public static class DetailsActivity ex
What is the purpose of this check?
To not add the fragment twice, though I prefer checking to see if the fragment is there instead of relying on that Bundle
being null
.
What would happen if it is not there?
Initially, nothing, as the Bundle
will be null
when the activity is first created.
However, then, the user rotates the device's screen from portrait to landscape. Or, the user changes languages. Or, the user puts the device into a manufacturer-supplied car dock. Or, the user does any other configuration change.
Your activity will be destroyed and recreated by default. Your fragments will also be destroyed and recreated by default (exception: those on which setRetainInstance(true)
are called, which are detached from the old activity and attached to the new one).
So, the second time the activity is created -- the instance created as a result of the configuration change -- your fragment already exists, as it was either recreated or retained. You don't want a second instance of that fragment (usually), and therefore you take steps to detect that this has occurred and not run a fresh FragmentTransaction
.