Search code examples
javaandroidandroid-fragmentsillegalstateexception

Why is this "IllegalStateException: Fragment already added" error happening?


(It was suggested that this is a duplicate question. I believe it is unique because I have to return myFragment)

I'm getting an error :

IllegalStateException: Fragment already added

Any idea why this is happening? The following is in my fragment adapter:

@Override
 public Fragment getItem(int position) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        MyFragment myFragment = new MyFragment();
        fragmentTransaction.add(R.id.myViewPager, myFragment, "myFrag");
        fragmentTransaction.commit();

        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        myFragment.setArguments(bundle);

       return myFragment;
    }

Solution

  • This happens when we try to add the same fragment or DialogFragment twice before dismissing,

    if(mFragment.isAdded()) { return; }