0

I am updating an activity on my onPostexecute method of an AsyncTask. But now I have discovered and error.

If I open my activity and then press back before the async task has executed. The app dies,

Now this makes sense because it will try to update the activity which has jsut been closed.

How do i resolve this issue?

is there a check i can do in the onPostExecute method?

I Have an activity with multiple fragments in it. each fragment starts its own asynctask.

Zapnologica
  • 22,170
  • 44
  • 158
  • 253

1 Answers1

0

If you run task in fragment. isAdded() checks if your current fragment attached to activity, if not you'll get NPE on getActivity() call

    @Override
    protected void onPostExecute(Object result){
       if (isAdded()){
          // update fragment UI here  

       }
    }

if you run task from activity, you can hold activity reference as task field and check if not null in onPostExecute, or you can hold some flag and switch it ib onStart and onStop

Georgy Gobozov
  • 13,633
  • 8
  • 72
  • 78