Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

PJL picture PJL · Apr 27, 2011 · Viewed 137.8k times · Source

I'm using the Android Compatibility library to implement fragments and have extended the layout sample so that a fragment contains a button which fires off another fragment.

In the selection pane on the left I have 5 selectable items - A B C D E.

Each loads up a fragment (via FragmentTransaction:replace) in the details pane - a b c d e

Now I've extended fragment e to contain a button which loads up another fragment e1 also in the details pane. I've done this on fragment e's onClick method as follows:

FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.details_frag, newFrag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();

If I make the following selections:

E - e - e1 - D - E

Then fragment e is in the details pane. This is fine and what I want. However, if I hit the back button at this point it does nothing. I have to click it twice because e1 is still on the stack. Furthermore after clicking around I got a null pointer exception in onCreateView:

To 'solve' this problem I added the following whenever A B C D E is selected:

FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
    fm.popBackStack();
}

Just wondering whether this is the correct solution or whether I should be doing something different?

Answer

Joachim picture Joachim · May 12, 2011

Well there are a few ways to go about this depending on the intended behavior, but this link should give you all the best solutions and not surprisingly is from Dianne Hackborn

http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42

Essentially you have the following options

  • Use a name for your initial back stack state and use FragmentManager.popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE).
  • Use FragmentManager.getBackStackEntryCount()/getBackStackEntryAt().getId() to retrieve the ID of the first entry on the back stack, and FragmentManager.popBackStack(int id, FragmentManager.POP_BACK_STACK_INCLUSIVE).
  • FragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE) is supposed to pop the entire back stack... I think the documentation for that is just wrong. (Actually I guess it just doesn't cover the case where you pass in POP_BACK_STACK_INCLUSIVE),