Show DialogFragment from onActivityResult

情到浓时终转凉″ 提交于 2019-11-27 04:09:59

问题


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.


回答1:


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



回答2:


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.




回答3:


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:

  • No need to add faux delays using threads, handlers or sleeps.
  • No need to commit allowing state loss or subclass to override show(). It is NOT a bug, it's a warning. Don't throw away state data. (Another one, bonus example)
  • No need to keep track of dialog fragments in your activity (hello memory leaks!)
  • And by God, no need to mess around with the activity lifecycle by calling onStart() manually.

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.

  • No need to write any code for onSaveInstanceState() (Another one)



回答4:


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.




回答5:


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.




回答6:


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."




回答7:


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.




回答8:


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



回答9:


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.




回答10:


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...




回答11:


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



回答12:


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



回答13:


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.
}



回答14:


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

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

If still not working, this post (Show DialogFragment from onActivityResult) helps me to solve the issue.




回答15:


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
}



回答16:


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




回答17:


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
}


来源:https://stackoverflow.com/questions/10114324/show-dialogfragment-from-onactivityresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!