How to show toast in AsyncTask in doInBackground

Write the following code where you have to show toast in doInBackground() method

runOnUiThread(new Runnable() {

public void run() {

  Toast.makeText(getApplicationContext(), "Example for Toast", Toast.LENGTH_SHORT).show();

   }
});
  • BTW: if you are using Fragments, you need to call runOnUiThread(...) through your activity:

getActivity().runOnUiThread(...)


You could wrap the Toast in runOnUIThread() but this isn't the best solution.
You should set a boolean flag in the catch block when an error occurs, then display an appropriate Toast in onProgressUpdate(), onPostExecute(), or any of the other methods with UI access whenever the flag is true.


You can display it in a method, that has access to the UI thread like onPreExecute(), onProgressUpdate() and onPostExecute()


return from doInBackground as

protected String doInBackground(String... params){
    //some code
    try{
       //some code
     }catch(Exception e){
        return "Exception Caught";
     }
     return someValidResult;
}

protected void onPostExecute(String result){
    if(result.equalsIgnoreCase("Exception Caught")){
       //Display Toast
    }else{
       // // whatever you wana do with valid result
    }
}