IllegalStateException: Fragment already added in the tabhost fragment
Solution 1
This happens when we try to add same fragment or DialogFragment twice before dismissing,
just call
if(mFragment.isAdded())
{
return; //or return false/true, based on where you are calling from
}
Having said that, I don't see any reason why to remove old fragment and add the same fragment again since we can update the UI/data by simply passing parameters to the method inside the fragment
Solution 2
Remove the old fragment in case it is still added and then add the new fragment:
FragmentManager fm = getSupportFragmentManager();
Fragment oldFragment = fm.findFragmentByTag("fragment_tag");
if (oldFragment != null) {
fm.beginTransaction().remove(oldFragment).commit();
}
MyFragment newFragment = new MyFragment();
fm.beginTransaction().add(newFragment , "fragment_tag");
Solution 3
You just have to check one condition in your fragment mentioned below:
if(!isAdded())
{
return;
}
isAdded = Return true if the fragment is currently added to its activity. Taken from the official document.
This will not add that fragment if it is already added
Check below link for a reference:
http://developer.android.com/reference/android/app/Fragment.html#isAdded()
Solution 4
Sometimes it happens for not finding proper id from the respective layout. I faced this problem. Then after many hours I found that I set wrong recyclerview id. I change it, and works fine for me.
So, double check your fragment layout.
Solution 5
You just have to check one condition before start fragment transaction
if (!fragmentOne.isAdded()){
transaction = manager.beginTransaction();
transaction.add(R.id.group,fragmentOne,"Fragment_One");
transaction.commit();
}
this is working perfactly for me...
Comments
-
user782104 almost 2 years
FATAL EXCEPTION: main Process: com.example.loan, PID: 24169 java.lang.IllegalStateException: Fragment already added: FormFragment{428f10c8 #1 id=0x7f050055 form} at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1192) at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:722) at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1533) at android.support.v4.app.FragmentManagerImpl$2.run(FragmentManager.java:489) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484) at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:450) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5068) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608) at dalvik.system.NativeStart.main(Native Method)
So, I have an android app that build with the tabhost. There are three tabs in total, in the tab2, there is a button to make the fragment transaction in tab2 (which is calling the function in the fragment activity)
FragmentTransaction t = getSupportFragmentManager().beginTransaction(); t.replace(R.id.realtabcontent, mFrag); t.addToBackStack(null); t.commit();
There is exception if I run like this:
- Inside the tab2, I press the button to change fragment
- Go to other tab (eg. tab 1 or tab 3)
- Press back button
- Throw exception
How to fix that? Thanks for helping
-
user782104 over 9 yearsthanks for your help, do you mean I put the if(!isAdded()) inside oncreateview?
-
Deep Mehta over 9 yearsYes, you just have to put that code i have mentioned in my answer above...It means that your fragment is already added in the stack. So, no need to add it again and it returns simply.
-
Fonix over 9 yearsthis makes no sense, you cant return void in onCreateView, did you mean onCreate? i tried this in there and it didnt help my issue
-
StuStirling about 9 yearsIs this added to
onCreate
? -
Alen Siljak over 8 yearsWhy the negation sign? Shouldn't the fragment be added if !isAdded() ?
-
AndroidDev over 8 yearsThis should be the accepted answer. The accepted answer makes no sense. First, there should be no negation of
isAdded()
. Second, in the comments, it is suggested that this code goes inonCreate()
, which is also nonsensical. This line of code should be placed directly before the line where the fragment is added (or replaced), not inonCreate()
oronCreateView()
. It's too late to execute that code in either of those methods. -
SqueezyMo about 6 yearsThanks, it was the same for me. The exception message couldn't be more misleading.
-
Konstantin Konopko about 6 years
if(fragment.isAdded()) fragmentTransaction.show(fragment);
-
Ujju almost 6 yearsshouldn't we send arguments to make any changes to the already displayed fragment? instead of removing and adding it again
-
vovahost almost 6 yearsYou cannot set the arguments after the fragment was added to the fragment manager. From docs: "This method cannot be called if the fragment is added to a FragmentManager and if isStateSaved() would return true." So you need to call your fragment methods directly if you want to update UI.
-
Ujju almost 6 yearsyes, I didn't mean setting via
setArguments
, was referring to sending arguments as params to update, so removing and adding the same fragment has no use right ? -
vovahost almost 6 yearsIt depends. If you need to reconfigure a lot of things it may be easier to just replace the fragment with a new one. It all depends of your needs.
-
Zun about 5 yearsThis answer is such a mess
-
CoolMind about 5 yearsIs it better to have 2 transactions instead of 1?
-
vovahost about 5 yearsNot really, using a single transaction should work as well.
-
Mahdi Moqadasi about 5 yearsalso must be checked for hiding fragments.
-
CoolMind almost 5 yearsI continue receiving the error, if use one transaction. Probably this is due to asynchronous behaviour of work with fragment manager.
-
CoolMind almost 5 yearsWhat will happen with old and new fragments? Will it replace old with new?
-
Muhammad Noman almost 5 yearsNo, it will not replace it will add the previous fragment to back stack.
-
CoolMind almost 5 yearsI wonder, is it possible? Yesterday I tried similar code and got an error, see stackoverflow.com/questions/38566628/…, because
addToBackStack
is not allowed together withcommitNow
. -
Muhammad Noman almost 5 yearsIn that link, he is manually disabling the back stack. With addToBackStack it will enable to manage back stack of fragment
-
Alston over 4 yearsI need to add similar fragments and only attributes in the fragment are different. But duplicated error still occurs.
-
Mitch over 4 yearsHow did you solve this? It's very similar to my use-case
-
Mitch over 4 years@Fonix use
onViewCreated(...)
to do the check -
CoolMind over 4 years@Mitch, I wrote
return tabs[position]
in the second line. -
Mitch over 4 yearsI'm also using the same concept as
return tabs[position]
but it still throws an error -
CoolMind over 4 years@Mitch, sorry, I don't know without a code. For general case currently I use stackoverflow.com/a/57161814/2914140. Do you think
FragmentStatePagerAdapter
throws the error ingetItem
? -
Mitch over 4 yearsIt's very likely to be the source of the error since it's where the instance(s) of the fragment(s) shown by the
ViewPager
are retrieved -
Mitch over 4 yearsjust posted a question stackoverflow.com/questions/58549379/… with my sample code. Kindly take a look at it to gain a better understanding of my situation
-
Omid Heshmatinia over 4 yearsAfter more than one month for investigating the root cause, This was the reason. Thanks a lot
-
Navin almost 4 yearsi had already implemented to check if fragment already added then return (the code of add fragment will not be executed) , as the my application is live on the play store still i got the crash fragment is already added from the some of the devices not all the devices i am trying to figure it out from the month ago, i can not over come it, i had applied numbers of solutions and update the build on the live play store, still i am receiving the error from the some of the devices like Galaxy S20+ 5G, huawei , there fewer devices that have the issue i got, any help would be appreciated thanks
-
Momin Khan over 2 yearsThanks, this was the issue, and it is absurd that the exception message lead us all here just to find out that the view id was wrong.
-
Admin over 2 years一般情况下,用户通过手动点击UI界面,触发的弹框。使用上面的方式是没有问题的。但是有时候,我们会根据设备的一些状态来选择弹框,比如网络的状态,蓝牙的连接状态。这些弹框的时机是无法把控的。可能会存在同一时间内的不同代码片段触发的多次弹框。我们知道commit的操作是异步的。这就导致了这种检查存在问题。比如前一个代码片段执行了commit的操作,在0.01秒后,另一个代码片段执行了检查并添加,此时前一个commit还未执行,导致后一个检查通过,再次添加fragment。此时就会导致重复添加的问题。要解决此类的问题,1.从业务层面避免这种逻辑。2.使用commitNow()。如果是DialogFragment,可以使用showNow()。