How to display a Toast in Android AsyncTask?

You cannot update UI on background thread. doInBackground() is invoked on the background thread. You should update UI on the UI thread.

      runOnUiThread(new Runnable(){

          @Override
          public void run(){
            //update ui here
            // display toast here 
          }
       });

onPreExecute(), onPostExecute(Result), are invoked on the UI thread. So you can display toast here.

onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...) can be used to animate a progress bar or show logs in a text field.

The result of doInBackground() computation is a parameter to onPostExecute(Result) so return the result in doinBackground() and show your toast in onPostExecute(Result)

You can also use a handler as suggested by @Stine Pike

For clarity, check the link below under the topic: The 4 steps.

http://developer.android.com/reference/android/os/AsyncTask.html

Leave a Comment