onActivityResult()片段事务错误

时间:2015-12-29 13:22:24

标签: android android-fragments

我正在尝试替换fragment中的onActivityResult(),但它总是给我java.lang.illegalStateException.的错误

Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
12-29 18:50:21.455 5554-5554/com.package E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1377)
12-29 18:50:21.455 5554-5554/com.package E/AndroidRuntime:     at     android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1395)
12-29 18:50:21.455 5554-5554/com.package E/AndroidRuntime:     at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:637)
12-29 18:50:21.455 5554-5554/com.package E/AndroidRuntime:     at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:616)
12-29 18:50:21.455 5554-5554/com.package E/AndroidRuntime:     at .virtualClass.VirtualPurchaseFragment.dealWithSuccessfulPurchase(VirtualPurchaseFragment.java:161)

这是我的onActivityResult代码

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    Fragment fragment = new VirtualListFragment();
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();

}

3 个答案:

答案 0 :(得分:15)

终于找到了解决方案,片段无法在onActivityResult()中交换或替换

我们需要将此代码放在HandlerOnResume()

解决方案:

private boolean change_fragment=false;

OnActivityResult()代码

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    change_fragment=true;
}

OnResume()代码

@Override
public void onResume() {
    super.onResume();
    if(change_fragment)
    {
        change_fragment=false;
        Fragment fragment = new VirtualListFragment();
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
    }
}

答案 1 :(得分:3)

这个问题的答案是你不应该在活动加载它的savedInstanceState之前或者在它保存了savedInstanceState之后调用片段事务上的commit。

这个问题的现有答案之一提到Activity#onResume()作为提交片段事务的地方但是Activity#onPostResume()将是一个更好的选择,因为当活动的实例状态被保证时它被调用恢复。

本博文中提供了对正在发生的事情及其发生原因的详细解释:http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html

答案 2 :(得分:0)

你试过这个吗?希望这个帮助

您需要从主要活动中获得fragment manager

请尝试以下代码段: -

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

    if(requestCode == 1){
        if(resultCode == Activity.RESULT_OK){
            android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new DemoFragment(), "fsdf").commit();
        }
    }
}