Show DialogFragment from onActivityResult

AndroidAndroid FragmentsAndroid Dialogfragment

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

EDIT: Not a bug, but more of a deficiency in the fragments framework. The better answer to this question is the one provided by @Arcao above.

---- Original post ----

Actually it's a known bug with the support package (edit: not actually a bug. see @alex-lockwood's comment). A posted work around in the comments of the bug report is to modify the source of the DialogFragment like so:

public int show(FragmentTransaction transaction, String tag) {
    return show(transaction, tag, false);
}


public int show(FragmentTransaction transaction, String tag, boolean allowStateLoss) {
	transaction.add(this, tag);
    mRemoved = false;
    mBackStackId = allowStateLoss ? transaction.commitAllowingStateLoss() : transaction.commit();
    return mBackStackId;
}

Note this is a giant hack. The way I actually did it was just make my own dialog fragment that I could register with from the original fragment. When that other dialog fragment did things (like be dismissed), it told any listeners that it was going away. I did it like this:

public static class PlayerPasswordFragment extends DialogFragment{

 Player toJoin;
 EditText passwordEdit;
 Button okButton;
 PlayerListFragment playerListFragment = null;

 public void onCreate(Bundle icicle){
   super.onCreate(icicle);
   toJoin = Player.unbundle(getArguments());
   Log.d(TAG, "Player id in PasswordFragment: " + toJoin.getId());
 }

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle icicle){
     View v = inflater.inflate(R.layout.player_password, container, false);
     passwordEdit = (EditText)v.findViewById(R.id.player_password_edit);
     okButton = (Button)v.findViewById(R.id.ok_button);
     okButton.setOnClickListener(new View.OnClickListener(){
       public void onClick(View v){
         passwordEntered();
       }
     });
     getDialog().setTitle(R.string.password_required);
     return v;
 }

 public void passwordEntered(){
   //TODO handle if they didn't type anything in
   playerListFragment.joinPlayer(toJoin, passwordEdit.getText().toString());
   dismiss();
 }

 public void registerPasswordEnteredListener(PlayerListFragment playerListFragment){
   this.playerListFragment = playerListFragment;
 }

 public void unregisterPasswordEnteredListener(){
   this.playerListFragment = null;
 }
}

So now I have a way to notify the PlayerListFragment when things happen. Note that its very important that you call unregisterPasswordEnteredListener appropriately (in the above case when ever the PlayerListFragment "goes away") otherwise this dialog fragment might try to call functions on the registered listener when that listener doesn't exist any more.

Solution 3 - Android

The comment left by @Natix is a quick one-liner that some people may have removed.

The simplest solution to this problem is to call super.onActivityResult() BEFORE running your own code. This works regardless if you're using the support library or not and maintains behavioural consistency in your Activity.

There is:

The more I read into this the more insane hacks I've seen.

If you're still running into issues, then the one by Alex Lockwood is the one to check.

Solution 4 - Android

I believe it is an Android bug. Basically Android calls onActivityResult at a wrong point in the activity/fragment lifecycle (before onStart()).

The bug is reported at https://issuetracker.google.com/issues/36929762

I solved it by basically storing the Intent as a parameter I later processed in onResume().

[EDIT] There are nowadays better solutions for this issue that were not available back in 2012. See the other answers.

Solution 5 - Android

EDIT: Yet another option, and possibly the best yet (or, at least what the support library expects...)

If you're using DialogFragments with the Android support library, you should be using a subclass of FragmentActivity. Try the following:

onActivityResult(int requestCode, int resultCode, Intent data) {
   
   super.onActivityResult(requestCode, resultCode, intent);
   //other code

   ProgressFragment progFragment = new ProgressFragment();  
   progFragment.show(getActivity().getSupportFragmentManager(), PROG_DIALOG_TAG);

   // other code
}

I took a look at the source for FragmentActivity, and it looks like it's calling an internal fragment manager in order to resume fragments without losing state.


I found a solution that's not listed here. I create a Handler, and start the dialog fragment in the Handler. So, editing your code a bit:

onActivityResult(int requestCode, int resultCode, Intent data) {

   //other code

   final FragmentManager manager = getActivity().getSupportFragmentManager();
   Handler handler = new Handler();
   handler.post(new Runnable() {
       public void run() {
           ProgressFragment progFragment = new ProgressFragment();  
           progFragment.show(manager, PROG_DIALOG_TAG);
       }
   }); 
  
  // other code
}

This seems cleaner and less hacky to me.

Solution 6 - Android

There are two DialogFragment show() methods - show(FragmentManager manager, String tag) and show(FragmentTransaction transaction, String tag).

If you want to use the FragmentManager version of the method (as in the original question), an easy solution is to override this method and use commitAllowingStateLoss:

public class MyDialogFragment extends DialogFragment {

  @Override	
  public void show(FragmentManager manager, String tag) {
      FragmentTransaction ft = manager.beginTransaction();
      ft.add(this, tag);
      ft.commitAllowingStateLoss();
  }

}

Overriding show(FragmentTransaction, String) this way is not as easy because it should also modify some internal variables within the original DialogFragment code, so I wouldn't recommend it - if you want to use that method, then try the suggestions in the accepted answer (or the comment from Jeffrey Blattman).

There is some risk in using commitAllowingStateLoss - the documentation states "Like commit() but allows the commit to be executed after an activity's state is saved. This is dangerous because the commit can be lost if the activity needs to later be restored from its state, so this should only be used for cases where it is okay for the UI state to change unexpectedly on the user."

Solution 7 - Android

You cannot show dialog after attached activity called its method onSaveInstanceState(). Obviously, onSaveInstanceState() is called before onActivityResult(). So you should show your dialog in this callback method OnResumeFragment(), you do not need to override DialogFragment's show() method. Hope this will help you.

Solution 8 - Android

I came up with a third solution, based partially from hmt's solution. Basically, create an ArrayList of DialogFragments, to be shown upon onResume();

ArrayList<DialogFragment> dialogList=new ArrayList<DialogFragment>();

//Some function, like onActivityResults
{
    DialogFragment dialog=new DialogFragment();
    dialogList.add(dialog);
}


protected void onResume()
{
    super.onResume();
    while (!dialogList.isEmpty())
        dialogList.remove(0).show(getSupportFragmentManager(),"someDialog");
}

Solution 9 - Android

onActivityResult() executes before onResume(). You need to do your UI in onResume() or later.

Use a boolean or whatever you need to communicate that a result has come back between both of these methods.

... That's it. Simple.

Solution 10 - Android

I know this was answered quite a while ago.. but there is a much easier way to do this than some of the other answers I saw on here... In my specific case I needed to show a DialogFragment from a fragments onActivityResult() method.

This is my code for handling that, and it works beautifully:

DialogFragment myFrag; //Don't forget to instantiate this
FragmentTransaction trans = getActivity().getSupportFragmentManager().beginTransaction();
trans.add(myFrag, "MyDialogFragmentTag");
trans.commitAllowingStateLoss();

As was mentioned in some of the other posts, committing with state loss can cause problems if you aren't careful... in my case I was simply displaying an error message to the user with a button to close the dialog, so if the state of that is lost it isn't a big deal.

Hope this helps...

Solution 11 - Android

It's an old question but I've solved by the simplest way, I think:

getActivity().runOnUiThread(new Runnable() {
    @Override
        public void run() {
            MsgUtils.toast(getString(R.string.msg_img_saved),
                    getActivity().getApplicationContext());
        }
    });

Solution 12 - Android

It happens because when #onActivityResult() is called, the parent activity has already call #onSaveInstanceState()

I would use a Runnable to "save" the action (show dialog) on #onActivityResult() to use it later when activity has been ready.

With this approach we make sure the action we want to will always work

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == YOUR_REQUEST_CODE) {
        mRunnable = new Runnable() {
            @Override
            public void run() {
                showDialog();
            }
        };
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

@Override
public void onStart() {
    super.onStart();
    if (mRunnable != null) {
        mRunnable.run();
        mRunnable = null;
    }
}

Solution 13 - Android

The cleanest solution I found is this:

@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
	new Handler().post(new Runnable() {
		@Override
		public void run() {
			onActivityResultDelayed(requestCode, resultCode, data);
		}
	});
}

public void onActivityResultDelayed(int requestCode, int resultCode, Intent data) {
	// Move your onActivityResult() code here.
}

Solution 14 - Android

I got this error while doing .show(getSupportFragmentManager(), "MyDialog"); in activity.

Try .show(getSupportFragmentManager().beginTransaction(), "MyDialog"); first.

If still not working, this post (https://stackoverflow.com/questions/10114324/show-dialogfragment-from-onactivityresult/10114942#10114942) helps me to solve the issue.

Solution 15 - Android

Another way:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case Activity.RESULT_OK:
            new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message m) {
                    showErrorDialog(msg);
                    return false;
                }
            }).sendEmptyMessage(0);
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
    }
}


private void showErrorDialog(String msg) {
    // build and show dialog here
}

Solution 16 - Android

just call super.onActivityResult(requestCode, resultCode, data); before handling the fragment

Solution 17 - Android

As you all know this problem is because of on onActivityResult() is calling before onstart(),so just call onstart() at start in onActivityResult() like i have done in this code

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      onStart();
      //write you code here
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKurtis NusbaumView Question on Stackoverflow
Solution 1 - AndroidArcaoView Answer on Stackoverflow
Solution 2 - AndroidKurtis NusbaumView Answer on Stackoverflow
Solution 3 - AndroidtwigView Answer on Stackoverflow
Solution 4 - AndroidhrntView Answer on Stackoverflow
Solution 5 - AndroidSimon JacobsView Answer on Stackoverflow
Solution 6 - AndroidgkeeView Answer on Stackoverflow
Solution 7 - AndroidhandrenliangView Answer on Stackoverflow
Solution 8 - AndroidPearsonArtPhotoView Answer on Stackoverflow
Solution 9 - AndroidEurig JonesView Answer on Stackoverflow
Solution 10 - AndroidJustinView Answer on Stackoverflow
Solution 11 - AndroidLucasBatalhaView Answer on Stackoverflow
Solution 12 - AndroidRicardView Answer on Stackoverflow
Solution 13 - AndroidfhuchoView Answer on Stackoverflow
Solution 14 - AndroidYoungjaeView Answer on Stackoverflow
Solution 15 - AndroidMaher AbuthraaView Answer on Stackoverflow
Solution 16 - AndroidThomas KlammerView Answer on Stackoverflow
Solution 17 - AndroidBunny BandewarView Answer on Stackoverflow