Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot save and restore a nested Fragment?

I have a nested Fragment that I am trying to restore the state given an orientation change.

So firstly my setup is as follows:

Activity -> ParentFragment (SetRetainInstance(true)) -> ChildFragment

In My Child fragment I have the onSaveInstance code as follows:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // Serialize the current dropdown position.
    outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActivity().getActionBar()
            .getSelectedNavigationIndex());
}

However when I orientate the device in all the LifeCycle events return a savedInstance state of null.

Am I doing this incorrectly for a ChildFragment? Why is my state not getting saved and returned?

like image 278
Donal Rafferty Avatar asked Sep 18 '14 12:09

Donal Rafferty


1 Answers

It's due to setRetainInstance(true) of your parent fragment. Android retains a fragment with all its children fragments. So your ChildFragment is not destroyed, and that's why you get null in savedInstanceState. The documentation of onCreateView states:

savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given here.

You can try to comment setRetainInstance(true) out and ensure you get correct value for savedInstanceState.

like image 193
Ayzen Avatar answered Oct 04 '22 13:10

Ayzen