搜尋此網誌

2015年9月20日 星期日

【Android】java.lang.IllegalStateException: Fragment not attached to Activity

ref:
http://stackoverflow.com/a/22544283

Generally you get that error when you try to perform work after the Fragment is no longer attached to the Activity. In the callback that triggers the IllegalStateException add a check for isAdded:http://developer.android.com/reference/android/app/Fragment.html#isAdded()
if(!isAdded()) {
    return;
}
http://stackoverflow.com/a/10941410
I've found the very simple answer: isAdded():
Return true if the fragment is currently added to its activity.
@Override
protected void onPostExecute(Void result){
    if(isAdded()){
        getResources().getString(R.string.app_name);
    }
}
To avoid onPostExecute from being called when the Fragment is not attached to the Activity is to cancel the AsyncTask when pausing or stopping the Fragment. Then isAdded() would not be necessary anymore.

沒有留言: