Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty savedInstanceState Bundle when restoring a Fragment after double Rotation in replacing Fragment

lets call them Fragment A and B. Fragment B is just a detailed view for A which replaces the Fragment A upon a click of a Button in Fragment A.

The replacement code:

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, new DetailFragment());
    transaction.addToBackStack(null);
    transaction.commit();

When I now rotate the screen in Fragment B once and press Back the old Fragment A gets restored without any problems (it restores it state in onActivityCreated with the savedInstanceState Bundle).

Now to the fun part...

When I rotate the screen in Fragment B more than once and press Back I get a NullPointerException because int[] data = savedInstanceState.getIntArray(STATE_DATA); in onActivityCreated returns null.

How can I fix this behavior? The only other way I though of was through permanent Storage(Preference or DB) but that seems very inappropriate for the use case.

edit/additional info: The bundle itself is not null, it's just empty

like image 956
algorithms Avatar asked Sep 30 '22 20:09

algorithms


1 Answers

Ok I found the answer:

The following methods from Fragment A get called on rotation change while Fragment B is active: onSaveInstanceState(), onAttach() and onCreate()

because I am restoring my state in onActivityCreated (which is actually recommended by the sdk!) I lose my variables stored in the bundle after the first rotation because they never get loaded into the local variables that then would be stored on the next onSaveInstanceState. Therefore those values are null when I try to retrieve them after the second rotation.

Solution: Restore the variables in onCreate() so that they are available when onSaveInstanceState is called again.

like image 138
algorithms Avatar answered Oct 10 '22 03:10

algorithms