11

I know there have been several questions about this exception, however, I'm experiencing this exception with only one assignment while using the FragmentStatePagerAdapter.

I indicated the line I'm experiencing the crash on below while setting up the adapter and pager.

Setting up my Fragments:

android.support.v4.app.FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.add(0, new StarTabFragment(), "starTab");
t.add(0, new HierarchiesTabFragment(), "hierarchyTab");
t.add(0, new GroupsTabFragment(), "groupTab");
t.add(0, new VehiclesTabFragment(), "hierarchyTab");
t.commit();

Setting up my adapter and pager:

viewPager = (ViewPager) mDrawerLayoutRight.findViewById(R.id.pager);
PagerTabStrip tabs = (PagerTabStrip) mDrawerLayoutRight.findViewById(R.id.pager_tab_strip);
tabs.setTabIndicatorColor(Color.RED);

CustomPagerAdapter customPagerAdapter = new CustomPagerAdapter(getSupportFragmentManager());
viewPager.setOffscreenPageLimit(customPagerAdapter.getCount() - 2);
viewPager.setAdapter(customPagerAdapter); //crashing here
viewPager.setOnPageChangeListener(new LoopingPageChangeListener(viewPager));
viewPager.setCurrentItem(1);

Stacktrace:

at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:876)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5343)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: java.lang.IllegalStateException: Fragment already added: StarTabFragment{d12eb55 #1 id=0x7f0b0116 starTab}
    at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1197)
    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:673)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
    at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
    at android.support.v4.view.ViewPager.setAdapter(ViewPager.java:447)
    at com.company.activities.MapsActivity.setupSliderRight(MapsActivity.java:847)
    at com.company.activities.MapsActivity.access$2100(MapsActivity.java:112)
    at com.company.activities.MapsActivity$DBHierarchyResponseReceiver.onReceive(MapsActivity.java:2287)
    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5343)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

5 Answers 5

14

It seems sometimes that this is a generic error thrown when something occurred while loading the fragment.

For example: I had this error when inside onCreateView I called findViewById with a wrong id that didn't exist on fragment's layout.

So, make sure your fragment onCreateView's code doesn't has any bug (try commenting it all - only returning the raw inflated view - and see if it still throws this error.

2
  • Thank you, this saved a lot of time! Jan 5, 2021 at 12:50
  • This comment is still useful. I findViewById to a wrong class, and got this error too. So weird why don't they just throw error like "Cannot cast class...." in my case... Aug 12, 2021 at 8:39
9

Its not necessary that problem is in with the way you are adding fragments. As i faced similar issue and later when i used debugger to go step by step to find real issue it turned out issue was with views in fragment layout.

I was getting similar exception like yours but real exception was

java.lang.ClassCastException:
6
  • 1
    Why down vote? You should reproduce the above issue first before down voting.
    – jatin rana
    Jan 30, 2019 at 8:46
  • You were right, I debugged the app step by step and found out that problem was elsewhere, thank you Apr 27, 2019 at 10:19
  • 1
    @Amin Keshavarzian Thanks for confirming.
    – jatin rana
    Apr 28, 2019 at 15:35
  • @jatin rana I've faced with the same issue related to fragment layout. And your comment helped me to resolve it. Thanks!
    – IgorOK
    Nov 22, 2019 at 0:06
  • @IgorOK Great buddy.
    – jatin rana
    Dec 19, 2019 at 19:00
5

The issue was that I was pre-adding the Fragments to the manager. FragmentPagerAdapter automatically adds all Fragments to the manager in the getItem() method.

Refer to this answer for details on the getItem() method.

0

Unsure if there are a lot of people who could be facing this issue due the same reason as me, but one tiny error that transitively kept causing java.lang.IllegalStateException: Fragment already added was that I was using a custom Fragment class.

In the onCreateView method, where I inflated my layout using inflater.inflate(), I forgot to use the method with attachToRoot as false. The moment I fixed this, my issue was resolved.

Explanation:

The method with signature:

inflate(@LayoutRes int resource, @Nullable ViewGroup root)

returned root (parent ViewGroup) and not the root of the newly inflated View. From the JavaDocs:

@return: The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.

A similar case could happen if you use the method: inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) with attachToRoot : true.

The Fragment tries to add the root layout as a child of itself, which causes java.lang.IllegalStateException: The specified child already has a parent

which snowballs into our original java.lang.IllegalStateException: Fragment already added.

Hope this helps someone.

0

I have experienced the exact same problem, and it turned out to be caused by copying of the fragment code. Android studio automatically refactored the methods, so I got this:

    public static Fragment newInstance(Bundle args) {
    PurchaseOfferFragment frag = new PurchaseOfferFragment();
    frag.setArguments(args);
    return  frag;
}

insteaf of this:

    public static PurchaseOfferFragment newInstance(Bundle args) {
    PurchaseOfferFragment frag = new PurchaseOfferFragment();
    frag.setArguments(args);
    return  frag;
}

resultin in the untrackable IlleGalStateException.

Causing the error which I couldn't track with the exception being thrown. Simply changing "Fragment" to PurchaseOfferFragment fixed the issue 100%.

Check if your fragment names are correct in the static mathods, while making a copy and paste from existing fragments, to save some hours that I have lost!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.