2017-05-04 89 views
-1

當試圖在接收到來自的AsyncTask的響應,以取代片段我收到一個下面的錯誤。在一個簡化版本,我的活動包含4種關鍵方法(的onCreate,taskCompleted,parseJSON和fragmentReplace),即確定哪些片段應用戶看到在開始:IllegalStateException異常上的AsyncTask

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

您應該閱讀WeakReference解決方案(或可能是其他人)在java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState


這個問題有一個備用解決方案。使用標誌,你可以處理它,就像下面

/** 
* 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(); 
    } 
} 
相關問題