DialogFragment display code example (just shows progress bar)

public void showProgressDialog(boolean isShow) { if(isShow){ if(!mProgressDialog.isAdded()) { mProgressDialog.show(getSupportFragmentManager(), ProgressDialog.TAG); } } else { mProgressDialog.dismiss(); } } 

In an application, a situation may arise when this function is called twice at the same time. For the test, you can simply do so

 public void showProgressDialog(boolean isShow) { if(isShow){ if(!mProgressDialog.isAdded()) { mProgressDialog.show(getSupportFragmentManager(), ProgressDialog.TAG); } } else { mProgressDialog.dismiss(); } if(isShow){ if(!mProgressDialog.isAdded()) { mProgressDialog.show(getSupportFragmentManager(), ProgressDialog.TAG); } } else { mProgressDialog.dismiss(); } } 

This code will crash with

 Fatal Exception: java.lang.IllegalStateException: Fragment already added: ProgressDialog{fffc31f #2 ProgressDialog} at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1892)... 

As I understand it, adding a fragment happens asynchronously, and therefore isAdded () returns false.

Actually the question is: can this be avoided without entering additional flags / variables?

  • one
    And if you try to look for a fragment by tag? - post_zeew
  • @post_zeew tried, returns null - Art7
  • one
    Try to execute executePendingTransactions after the show . - post_zeew
  • IllegalStateException crashes: FragmentManager is already executing transactions - Art7

1 answer 1

The same problem was. Solved the problem as advised @post_zeew.

Old code:

 private void showDialogCreateOrEditPhoto(Bundle args, String tag){ PhotoDialogFragment photoDialog = PhotoDialogFragment.newInstance(this); photoDialog.setArguments(args); photoDialog.show(getFragmentManager(), tag); } 

New code:

 private void showDialogCreateOrEditPhoto(Bundle args, String tag){ FragmentManager fm = getFragmentManager(); Fragment fragment = fm.findFragmentByTag(tag); if (fragment == null) { //Если еще нет такого диалога, то создаем, иначе ничего PhotoDialogFragment photoDialog = PhotoDialogFragment.newInstance(this); photoDialog.setArguments(args); photoDialog.show(getFragmentManager(), tag); } } 

The showDialogCreateOrEditPhoto method worked when clicking on a list item. Accordingly, you can press several times until the dialog opens.

It is now checked that if there is a dialogue with such a tag, then it does nothing.