2

I am trying to prevent my DialogFragment opening twice. Here is what I do:

I try to keep only one instance of my fragment. I create and add my fragment like this:

//MyFragment.java

public static MyFragment mInstance;    

public static void instantiateFragment() {
    MyFragment myFragment = MyFragment.getInstance();

    if(!myFragment.isAdded()) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(myFragment, TAG);
        ft.commit();
    }
}

private static MyFragment getInstance() {
    if(mInstance == null) {
        mInstance = new MyFragment();
    }
    return mInstance;
}

And when a button is clicked, I intentionally try to add fragment twice like this:

MyFragment.instantiateFragment();
MyFragment.instantiateFragment();

But I get IllegalStateException: Fragment already added. Any ideas about that?

Thanks.

yrazlik
  • 10,411
  • 33
  • 99
  • 165

2 Answers2

2

Indeed it's a problem with asynchronous commit of transactions, so as @Android jack stated you can use executePendingTransactions() like in this answer, or even better use commitNow(),
or try something like this:

public static void instantiateFragment() {
    Fragment myFragment = getSupportFragmentManager().findFragmentByTag(TAG);

    if (myFragment == null) {
        myFragment = MyFragment.getInstance();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(myFragment, TAG);
        ft.commit();
    }
}
Community
  • 1
  • 1
makvasic
  • 213
  • 1
  • 8
1

I think this has to do with the asynchronous behaviour of fragment transactions.Fragment Transactions are committed asynchronously. So at first call, your fragment is added but it is committed asynchronously.Again in your next call your fragment is not added as it is not committed yet so !myFragment.isAdded() returns false.Then while adding the fragment the previous transaction is committed due to which it raises exception.
Try to use this

getFragmentManager().executePendingTransactions(); 

before your (!myFragment.isAdded()) code.

Rajesh Gosemath
  • 1,812
  • 1
  • 17
  • 31