Reputation: 1897
What is the best way to clear fragment back stack programmatic?
I've implemented screen navigation using only one activity and set of fragments. I would like to have method that brings user to the login screen(when logout timeout expires) and clears all fragment history, what is the best way to do that? I found few answers here yet I've dont know which is the best one...Thanks in advance!
for the moment I'm using this one
public void clearBackStack() {
FragmentManager fragmentManager = holder.getSupportFragmentManager();
while (fragmentManager.getBackStackEntryCount() != 0) {
fragmentManager.popBackStack(null, 0);
}
}
Yet sometimes I'm getting outOfMemoryException
Upvotes: 3
Views: 13039
Reputation: 3
You can use FragmentManager.popBackStack()
to clear the backstack.
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
This will empty the stack without loading into the container.
Upvotes: 0
Reputation: 155
This is a pretty old question at this point. Anyway I tried your code and it looks like you've got an infinite loop.
popBackStack(null, 0)
searches for a fragment with a null tag, which will never be found. The while loop will cycle until memory runs out. The other issue with popBackStack
is that the pop is not necessarily immediately performed so the while loop could run for a while.
If you want to remove fragments from the back stack irrespective of tag or ID, use fragmentManager.popBackStackImmediate()
instead.
Upvotes: 13