Show DialogFragment from onActivityResult

Kurtis Nusbaum picture Kurtis Nusbaum · Apr 11, 2012 · Viewed 38.6k times · Source

I have the following code in my onActivityResult for a fragment of mine:

onActivityResult(int requestCode, int resultCode, Intent data){
   //other code
   ProgressFragment progFragment = new ProgressFragment();  
   progFragment.show(getActivity().getSupportFragmentManager(), PROG_DIALOG_TAG);
   // other code
}

However, I'm getting the following error:

Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState   

Anybody know what's going on, or how I can fix this? I should note I'm using the Android Support Package.

Answer

Arcao picture Arcao · Apr 4, 2013

If you use Android support library, onResume method isn't the right place, where to play with fragments. You should do it in onResumeFragments method, see onResume method description: http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#onResume%28%29

So the correct code from my point of view should be:

private boolean mShowDialog = false;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
  super.onActivityResult(requestCode, resultCode, data);

  // remember that dialog should be shown
  mShowDialog = true;
}

@Override
protected void onResumeFragments() {
  super.onResumeFragments();

  // play with fragments here
  if (mShowDialog) {
    mShowDialog = false;

    // Show only if is necessary, otherwise FragmentManager will take care
    if (getSupportFragmentManager().findFragmentByTag(PROG_DIALOG_TAG) == null) {
      new ProgressFragment().show(getSupportFragmentManager(), PROG_DIALOG_TAG);
    }
  }
}