0

(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;
    }

1 Answers1

0

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

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

  • In the code I provided, did I add the fragment twice? Also, I need to return a fragment. If "myFragment" is already added I'm not sure what to do. – genericName May 07 '19 at 06:50
  • @genericName You are not adding it twice but it happens sometimes when your activity goes in the background and then reappears. – Ranjan May 07 '19 at 07:32