I am working on an Android app and have encountered an error involving Fragments and FragmentTransactions. I have created an example app to demonstrate the problem. Here is what I am doing:
add
Fragment1
tofragmentSpace
, without adding to backstack.replace
fragmentSpace
withFragment2
, adding to backstack as"beginning"
.add
Fragment3
tofragmentSpace2
(which is inside ofFragment2
), without adding to backstack.replace
fragmentSpace2
withFragment4
, adding to backstack asnull
.- Call
getFragmentManager().popBackStack("beginning", FragmentManager.POP_BACK_STACK_INCLUSIVE);
in an attempt to undo all the Transactions, which should bring the user back to seeing onlyFragment1
.
However, the app crashes on step 5 with this error:
java.lang.IllegalArgumentException: No view found for id 0x7f090004 (me.MitchT.testfragmenttransactions:id/fragmentSpace2) for fragment Fragment3{7f35cb6 #2 id=0x7f090004}
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:886)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.app.BackStackRecord.popFromBackStack(BackStackRecord.java:1645)
...
I have found that if I add step 3 to the backstack, step 5 no longer crashes the app and there is no more error. Why?
The problem I have with adding step 3 to the backstack is that I want the user to be able to press the back button after Fragment3
is added and go back to Fragment1
. If I add it to the backstack, then when the user presses the back button it removes Fragment3
, but Fragment2
is still visible, so they must press the back button again. I am trying to avoid that double-back-button behavior.
I did not feel it was necessary to post the code for every single file in the example app on this question, so instead I created a gist.
So I guess my questions are:
- Why do I get this error?
- Why don't I get the error after adding step 3 to the backstack?
- Is there a better way of "going back to the beginning" or going back two fragments at a time?
Thanks!