How to show toast in AsyncTask in doInBackground
In one of my activities I'm using AsyncTask
. In doInBackground()
I'm making calls to various methods. In one of these methods I'm getting an exception, so in the catch block I want to show the error in the Toast.
I know I can use Log
, but still I prefer Toast.
So, how can I use Toast in AsyncTask in doInBackground()?
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
}
}
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
.