When my app starts I dinamically add a fragment instance (say, fragment1
) to the content layout in a transaction which is not added to the back stack. This fragment displays some cached data which has been passed to it by means of a newInstance(List<Obj>)
static method. In onSaveInstanceState()
I save the data so I can display it if the fragment is recreated.
Now suppose I don't recreate the fragment. Suppose I replace it with a second fragment, say, fragment2
(adding the transaction to the back stack this time), perform two screen rotations, and press back. The app will pop the back stack and attempt to display fragment1
again which by its turn will attempt to display List<Obj>
which will be null
so a NullPointerException
will be thrown.
I understand this is because the fragment1
instance has never been saved in the first place, since it wasn't in the back stack and neither was on display when the device rotated.
My question is, what's the most appropriate way of supporting screen rotations in this case? I could save the initial transaction in the back stack and make onBackPressed()
verify that getSupportFragmentManager().getBackStackEntryCount() >= 1
before popping the back stack (I don't want the initial transaction to be popped because fragment1
is my initial screen) but I don't think this is the correct approach. Any ideas?