In Android Studio, I am getting this error in “doInBackground method”

As others have already pointed out, you have to be mindful of what runs on the main (UI) thread and what runs on background threads.

AsyncTask‘s doInBackground runs in a background thread so you cannot do anything UI related there, like showing a Toast or updating views.


A few other things to be mindful of are:

  • AsyncTask has now been deprecated and will not be available eventually.
  • Inner classes in java should be static (unless intended) to avoid leaking their parent class. In your code above the AsyncTask will prevent the GC from clearing the Activity reference if it was still running after the Activity has finished.
  • Similar to the previous point, the app would crash if the activity was destroyed before the AsyncTask finishes. Because when the AsyncTask finishes and tries to update the UI in onPostExecute there will be no views (null) to update.

Leave a Comment