IllegalStateException: Fragment already added in the tabhost fragment

116,571

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...

Share:
116,571
user782104
Author by

user782104

php

Updated on July 08, 2022

Comments

  • user782104
    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:

    1. Inside the tab2, I press the button to change fragment
    2. Go to other tab (eg. tab 1 or tab 3)
    3. Press back button
    4. Throw exception

    How to fix that? Thanks for helping

  • user782104
    user782104 over 9 years
    thanks for your help, do you mean I put the if(!isAdded()) inside oncreateview?
  • Deep Mehta
    Deep Mehta over 9 years
    Yes, 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
    Fonix over 9 years
    this 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
    StuStirling about 9 years
    Is this added to onCreate?
  • Alen Siljak
    Alen Siljak over 8 years
    Why the negation sign? Shouldn't the fragment be added if !isAdded() ?
  • AndroidDev
    AndroidDev over 8 years
    This 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 in onCreate(), which is also nonsensical. This line of code should be placed directly before the line where the fragment is added (or replaced), not in onCreate() or onCreateView(). It's too late to execute that code in either of those methods.
  • SqueezyMo
    SqueezyMo about 6 years
    Thanks, it was the same for me. The exception message couldn't be more misleading.
  • Konstantin Konopko
    Konstantin Konopko about 6 years
    if(fragment.isAdded()) fragmentTransaction.show(fragment);
  • Ujju
    Ujju almost 6 years
    shouldn't we send arguments to make any changes to the already displayed fragment? instead of removing and adding it again
  • vovahost
    vovahost almost 6 years
    You 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
    Ujju almost 6 years
    yes, 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
    vovahost almost 6 years
    It 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
    Zun about 5 years
    This answer is such a mess
  • CoolMind
    CoolMind about 5 years
    Is it better to have 2 transactions instead of 1?
  • vovahost
    vovahost about 5 years
    Not really, using a single transaction should work as well.
  • Mahdi Moqadasi
    Mahdi Moqadasi about 5 years
    also must be checked for hiding fragments.
  • CoolMind
    CoolMind almost 5 years
    I continue receiving the error, if use one transaction. Probably this is due to asynchronous behaviour of work with fragment manager.
  • CoolMind
    CoolMind almost 5 years
    What will happen with old and new fragments? Will it replace old with new?
  • Muhammad Noman
    Muhammad Noman almost 5 years
    No, it will not replace it will add the previous fragment to back stack.
  • CoolMind
    CoolMind almost 5 years
    I wonder, is it possible? Yesterday I tried similar code and got an error, see stackoverflow.com/questions/38566628/…, because addToBackStack is not allowed together with commitNow.
  • Muhammad Noman
    Muhammad Noman almost 5 years
    In that link, he is manually disabling the back stack. With addToBackStack it will enable to manage back stack of fragment
  • Alston
    Alston over 4 years
    I need to add similar fragments and only attributes in the fragment are different. But duplicated error still occurs.
  • Mitch
    Mitch over 4 years
    How did you solve this? It's very similar to my use-case
  • Mitch
    Mitch over 4 years
    @Fonix use onViewCreated(...) to do the check
  • CoolMind
    CoolMind over 4 years
    @Mitch, I wrote return tabs[position] in the second line.
  • Mitch
    Mitch over 4 years
    I'm also using the same concept as return tabs[position] but it still throws an error
  • CoolMind
    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 in getItem?
  • Mitch
    Mitch over 4 years
    It'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
    Mitch over 4 years
    just 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
    Omid Heshmatinia over 4 years
    After more than one month for investigating the root cause, This was the reason. Thanks a lot
  • Navin
    Navin almost 4 years
    i 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
    Momin Khan over 2 years
    Thanks, 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
    Admin over 2 years
    一般情况下,用户通过手动点击UI界面,触发的弹框。使用上面的方式是没有问题的。但是有时候,我们会根据设备的一些状态来选择‌​弹框,比如网络的状态,蓝牙的连接状态。这‌​些弹框的时机是无法把控的。可能会存在同一‌​时间内的不同代码片段触发的多次弹框。我们‌​知道commit的操作是异步的。这就导致‌​了这种检查存在问题。比如前一个代码片段执‌​行了commit的操作,在0.01秒后,‌​另一个代码片段执行了检查并添加,此时前一‌​个commit还未执行,导致后一个检查通‌​过,再次添加fragment。此时就会导‌​致重复添加的问题。要解决此类的问题,1.‌​从业务层面避免这种逻辑。2.使用comm‌​itNow()。如果是DialogFra‌​gment,可以使用showNow()。