Question: I have the following AsyncTask in a Fragment (the example is simplified for showing clearly the error):

```
private class LoginTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {

        // Do network login
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        FragmentActivity act = (FragmentActivity) getActivity();
        if (act != null && isAdded()) {
            act.getSupportFragmentManager().beginTransaction()
                    .add(new LoginDialogFragment(), "loginMessage").commit();
        }
    }

}

```

Once, leaving the app while the task was running I received an `IllegalStateException: Can not perform this action after onSaveInstanceState`.

I suppose it is because I called it between the onSaveInstanceState of the activiy and the unattachment of the fragment from the activity (or because the activity was unattached after the getActivity() call and the add-fragment call.

So how can I avoid this error in the future? Thanks!

Answer: 
In `onPause`, `onStop`, or `onDestroy`, call `.cancel()` on the `AsyncTask` (this may require that your `AsyncTask` is a member variable in your activity). Then, in your `onPostExecute()` method, check if the process was cancelled.

```
protected void onPostExecute(Void result) {
    if (!isCancelled()) { // Do stuff only if not cancelled
        FragmentActivity act = (FragmentActivity) getActivity();
        if (act != null && isAdded()) {
            act.getSupportFragmentManager().beginTransaction()
                    .add(new LoginDialogFragment(), "loginMessage").commit();
        }
    }
    return null;
}

```

NB: You may want to also check `isCancelled()` in any loop you have in `doInBackground()` so you don't keep doing stuff once the person has left the app.
The [isFinishing()](http://developer.android.com/reference/android/app/Activity.html#isFinishing%28%29) method should help you here.

```
@Override
    protected void onPostExecute(Void result) {
        FragmentActivity act = (FragmentActivity) getActivity();
        if (act != null && !act.isFinishing() && isAdded()) {
            act.getSupportFragmentManager().beginTransaction()
                    .add(new LoginDialogFragment(), "loginMessage").commit();
        }
    }

```