On showing dialog i get “Can not perform this acti

2019-01-21 05:16发布

Some users are reporting, if they use the quick action in the notification bar, they are getting a force close.

I show a quick action in the notification who calls the "TestDialog" class. In the TestDialog class after pressing the button "snooze", I will show the SnoozeDialog.

private View.OnClickListener btnSnoozeOnClick() {
    return new View.OnClickListener() {

        public void onClick(View v) {
            showSnoozeDialog();
        }
    };
}

private void showSnoozeDialog() {
    FragmentManager fm = getSupportFragmentManager();
    SnoozeDialog snoozeDialog = new SnoozeDialog();
    snoozeDialog.show(fm, "snooze_dialog");
}

The error is *IllegalStateException: Can not perform this action after onSaveInstanceState*.

The code line where the IllegarStateException gets fired is:

snoozeDialog.show(fm, "snooze_dialog");

The class is extending "FragmentActivity" and the "SnoozeDialog" class is extending "DialogFragment".

Here is the complete stack trace of the error:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1327)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1338)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
at android.support.v4.app.DialogFragment.show(DialogFragment.java:127)
at com.test.testing.TestDialog.f(TestDialog.java:538)
at com.test.testing.TestDialog.e(TestDialog.java:524)
at com.test.testing.TestDialog.d(TestDialog.java:519)
at com.test.testing.g.onClick(TestDialog.java:648)
at android.view.View.performClick(View.java:3620)
at android.view.View$PerformClick.run(View.java:14292)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4507)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)

I can't reproduce this error, but I am getting a lot of error reports.

Can anybody help that how can I fix this error?

13条回答
闹够了就滚
2楼-- · 2019-01-21 05:54

If the dialog is not really important (it is okay to not-show it when the app closed/is no longer in view), use:

boolean running = false;

@Override
public void onStart() {
    running = true;
    super.onStart();
}

@Override
public void onStop() {
    running = false;
    super.onStop();
}

And open your dialog(fragment) only when we're running:

if (running) {
    yourDialog.show(...);
}

EDIT, PROBABLY BETTER SOLUTION:

Where onSaveInstanceState is called in the lifecycle is unpredictable, I think a better solution is to check on isSavedInstanceStateDone() like this:

/**
 * True if SavedInstanceState was done, and activity was not restarted or resumed yet.
 */
private boolean savedInstanceStateDone;

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

    savedInstanceStateDone = false;
}

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

    savedInstanceStateDone = false;
}

protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    savedInstanceStateDone = true;
}


/**
 * Returns true if SavedInstanceState was done, and activity was not restarted or resumed yet.
 */
public boolean isSavedInstanceStateDone() {
    return savedInstanceStateDone;
}
查看更多
走好不送
3楼-- · 2019-01-21 06:01

This error appears to be occurring because input events (such as key down or onclick events) are getting delivered after onSaveInstanceState is called.

The solution is to override onSaveInstanceState in your Activity and cancel any pending events.

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        final View rootView = findViewById(android.R.id.content);
        if (rootView != null) {
            rootView.cancelPendingInputEvents();
        }
    }
}
查看更多
Bombasti
4楼-- · 2019-01-21 06:02

That mean you commit() (show() in case of DialogFragment) fragment after onSaveInstanceState().

Android will save your fragment state at onSaveInstanceState(). So, if you commit() fragment after onSaveInstanceState() fragment state will be lost.

As a result, if Activity get killed and recreate later the fragment will not add to activity which is bad user experience. That's why Android does not allow state loss at all costs.

The easy solution is to check whether state already saved.

boolean mIsStateAlreadySaved = false;
boolean mPendingShowDialog = false;

@Override
public void onResumeFragments(){
    super.onResumeFragments();
    mIsStateAlreadySaved = false;
    if(mPendingShowDialog){
        mPendingShowDialog = false;
        showSnoozeDialog();
    }
}

@Override
public void onPause() {
    super.onPause();
    mIsStateAlreadySaved = true;
}

private void showSnoozeDialog() {
    if(mIsStateAlreadySaved){
        mPendingShowDialog = true;
    }else{
        FragmentManager fm = getSupportFragmentManager();
        SnoozeDialog snoozeDialog = new SnoozeDialog();
        snoozeDialog.show(fm, "snooze_dialog");
    }
}

Note: onResumeFragments() will call when fragments resumed.

查看更多
干净又极端
5楼-- · 2019-01-21 06:04

please try to use FragmentTransaction instead of FragmentManager. I think the below code will solve your problem. If not, Please let me know.

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SnoozeDialog snoozeDialog = new SnoozeDialog();
snoozeDialog.show(ft, "snooze_dialog");

EDIT:

Fragment Transaction

Please check this link. I think it will solve you queries.

查看更多
不美不萌又怎样
6楼-- · 2019-01-21 06:04
  1. Add this class to your project: (must be in android.support.v4.app package)
package android.support.v4.app;


/**
 * Created by Gil on 8/16/2017.
 */

public class StatelessDialogFragment extends DialogFragment {
    /**
     * Display the dialog, adding the fragment using an existing transaction and then committing the
     * transaction whilst allowing state loss.
* * I would recommend you use {@link #show(FragmentTransaction, String)} most of the time but * this is for dialogs you reallly don't care about. (Debug/Tracking/Adverts etc.) * * @param transaction * An existing transaction in which to add the fragment. * @param tag * The tag for this fragment, as per * {@link FragmentTransaction#add(Fragment, String) FragmentTransaction.add}. * @return Returns the identifier of the committed transaction, as per * {@link FragmentTransaction#commit() FragmentTransaction.commit()}. * @see StatelessDialogFragment#showAllowingStateLoss(FragmentManager, String) */ public int showAllowingStateLoss(FragmentTransaction transaction, String tag) { mDismissed = false; mShownByMe = true; transaction.add(this, tag); mViewDestroyed = false; mBackStackId = transaction.commitAllowingStateLoss(); return mBackStackId; } /** * Display the dialog, adding the fragment to the given FragmentManager. This is a convenience * for explicitly creating a transaction, adding the fragment to it with the given tag, and * committing it without careing about state. This does not add the transaction to the * back stack. When the fragment is dismissed, a new transaction will be executed to remove it * from the activity.
* * I would recommend you use {@link #show(FragmentManager, String)} most of the time but this is * for dialogs you reallly don't care about. (Debug/Tracking/Adverts etc.) * * * @param manager * The FragmentManager this fragment will be added to. * @param tag * The tag for this fragment, as per * {@link FragmentTransaction#add(Fragment, String) FragmentTransaction.add}. * @see StatelessDialogFragment#showAllowingStateLoss(FragmentTransaction, String) */ public void showAllowingStateLoss(FragmentManager manager, String tag) { mDismissed = false; mShownByMe = true; FragmentTransaction ft = manager.beginTransaction(); ft.add(this, tag); ft.commitAllowingStateLoss(); } }
  1. Extend StatelessDialogFragment instead of DialogFragment
  2. Use the method showAllowingStateLoss instead of show

  3. Enjoy ;)

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-21 06:05

Many views post high-level events such as click handlers to the event queue to run deferred. So the problem is that "onSaveInstanceState" has already been called for the Activity but the event queue contains deferred "click event". Hence when this event is dispatched to your handler

at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)

and your code does show the IllegalStateException is thrown.

The simplest solution is to clean event queue, in onSaveInstanceState

protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // ..... do some work
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            findViewById(android.R.id.content).cancelPendingInputEvents();
        }
}
查看更多
登录 后发表回答