onActivityResult

时间:2017-03-17 17:53:36

标签: android android-fragments

我已将这段代码放在一个片段中:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        if (requestCode == READ_REQUEST && resultCode == Activity.RESULT_OK) {
            Uri uri;
            if (resultData != null) {
                uri = resultData.getData();
                getChildFragmentManager().beginTransaction().add(new MyFragment(), TAG).commit();
            }
        }
    }

然而,IllegalStateException崩溃了。在onSaveInstanceState()之后,活动无法创建/恢复事务。在onActivityResult()中从另一个片段启动片段的正确方法是什么?

logcat的:

03-17 18:55:37.372 26127 26127 E AndroidRuntime: Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1434)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1452)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.BackStackRecord.commitInternal(BackStackRecord.java:708)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.BackStackRecord.commit(BackStackRecord.java:672)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at com.xxxx.ttyy.ui.SettingsFragment.onActivityResult(Unknown Source)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.Activity.dispatchActivityResult(Activity.java:6956)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
03-17 18:55:37.372 26127 26127 E AndroidRuntime:    ... 9 more
03-17 18:55:37.377   878  3186 W ActivityManager:   Force finishing activity com.balda.intenttask/.ui.MainActivity

1 个答案:

答案 0 :(得分:0)

您可以使用commitAllowingStateLoss

来自文档:

  

commit()类似,但允许在活动之后执行提交   国家被保存。这很危险,因为如果提交可能会丢失   活动需要稍后从其状态恢复,所以这应该   仅用于可以更改UI状态的情况   意外地在用户身上。

尝试使用:

getChildFragmentManager().beginTransaction().add(new MyFragment(), TAG).commitAllowingStateLoss();