AsyncTask上的IllegalStateException

时间:2017-05-04 07:50:15

标签: android android-asynctask illegalstateexception

我在收到AsyncTask的响应时尝试替换片段时遇到以下错误:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

问题是,我通过Android Studio重启我的应用程序后随机收到此错误。在简化版本中,我的活动包含4个关键方法(onCreate,taskCompleted,parseJSON和fragmentReplace),它们确定用户在开始时应该看到哪个片段:

private AsyncTask mMyTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mMyTask = new AsyncTask(this, this);
    mMyTask.executeTaskCall("check_user");
}


@Override
public void taskCompleted(String results) {
    try {
        JSONObject jsonBody = new JSONObject(results);
        parseJSON(jsonBody);
    }
    catch (JSONException je){
    }
}

private void parseJSON(JSONObject jsonBody) throws JSONException {
    boolean userActive = jsonBody.getBoolean("result");

    if (userActive){
        fragmentReplace(new FirstFragment(), "FirstFragment");
    }
    else {
        fragmentReplace(new SecondFragment(), "SecondFragment");
    }
}

public void fragmentReplace(Fragment fragment, String fragmentTag){
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.layout_container, fragment, fragmentTag)
            .commit();
}

这种例外发生的原因是什么?这是随机的?

1 个答案:

答案 0 :(得分:2)

您应该在java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState阅读WeakReference解决方案(或者也可能是其他解决方案)。

此问题有一种替代解决方案。使用flag你可以处理它,如下面的

/**
 * Flag to avoid "java.lang.IllegalStateException: Can not perform this action after
 * onSaveInstanceState". Avoid Fragment transaction until onRestoreInstanceState or onResume
 * gets called.
 */
private boolean isOnSaveInstanceStateCalled = false;


@Override
public void onRestoreInstanceState(final Bundle bundle) {
    .....
    isOnSaveInstanceStateCalled = false;
    .....
}

@Override
public void onSaveInstanceState(final Bundle outState) {
    .....
    isOnSaveInstanceStateCalled = true;
    .....
}

@Override
public void onResume() {
    super.onResume();
    isOnSaveInstanceStateCalled = false;
    .....
}

您可以在执行片段事务时检查此boolean值。

private void fragmentReplace(Fragment fragment, String fragmentTag){
    if (!isOnSaveInstanceStateCalled) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.layout_container, fragment, fragmentTag)
                .commit();
    }
}

API 26.1+的更新(由Stephen M提供)

自26.1.0以来已添加

Fragment.isStateSaved(),也可用于相同目的。