I have 3 Fragments and the flow is like
Fragment 1 --> Fragment 2 (adding it to back stack)--> Fragment 3 --> Fragment 1
As I want to go to Fragment 1 from Fragment 3 again, I want the back stack to be clean so that when user press back nothing happens.
Intially I have cleared popback stack at Fragment 3
Boolean isPoped = fManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
And then created a new Instance of my fragment 1
HomeFragment homeFragment = HomeFragment.newInstance(mobileNumber, "");
FragmentTransaction transaction =fManager.beginTransaction();
transaction.replace(R.id.fragment_container, homeFragment);
transaction.commit();
which caused android: ViewPager throwing null pointer
then I commented the above code and only used
Boolean isPoped = fManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
which works fine as it removed the transactions(that I belive) and took me to homeFragment but that caused View pager not instantiating post fragment popBackStackImmediate
Here I am not getting how popBackStack works? All I want is to take user from Fragment 3 to Fragment 1 and clear the backstack.
I looked at your code in the other question and I think I understand what the problem is.
So your first action is that you create Fragment 1 and put it in a container. I don't see code for that but no matter; if the container is empty then
add
andreplace
act the same way. So now your Fragment 1 is in the container.You haven't called
addToBackStack
here so theFragmentManager
doesn't know how to undo this operation. That's fine, it's the first operation and doesn't need to be undone.Next you create Fragment 2 and do a
replace
transaction. Fragment 1 is replaced with Fragment 2. This is pushed to the back stack so theFragmentManager
does know how to undo this transaction.Next you create Fragment 3 and do a
replace
transaction. Fragment 2 is replaced with Fragment 3. You don't push this operation to the back stack. Uh oh.Now when you say
popBackStack
(deferred or immediate) theFragmentManager
goes to undo the operation to replace Fragment 2 with Fragment 1 but Fragment 2 isn't in the container anymore. So (from what I understand) theFragmentManager
will put Fragment 1 back in the container but leave Fragment 3 there. It doesn't know what to do with Fragment 3.Here is how I handle those kinds of scenarios: Say I have Fragment 1, then navigate to Fragment 2. To navigate to Fragment 3 when I intend the back button to go to Fragment 1, I do this:
Now when I press the back button, the
FragmentManager
knows how to undo my operation and puts Fragment 1 back where Fragment 3 was. This means that I don't have to perform any fragment transactions to handle this back navigation, theFragmentManager
handles it all for me.