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()?
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 .
A simpler way to do this is to overwrite the onStop and use getApplicationContext() . Then the toast will appear when the activity closes.
myActivity. runOnUiThread(new Runnable() { public void run() { Toast. makeText(myActivity, "Toast Message Text!", Toast.
Steps: declare a handler in the main activity (onCreate) now create a thread from the main activity and pass the Context of that activity. now use this context in the Toast, instead of using getApplicationContext()
show your Toast in onPostExecute or onPreExecute. doInBackGround runs on a separate thread but the other two methods run on the UI thread. But if it is must to show toast in doInBackGround then you can use Handler.post or runonUiThread to perform toast showing.
Looking to earn? AsyncTask (asynchronous task) is an Android class that makes it easier to do operations on a background thread and publish the result on the User Interface (UI)/ main thread without having to manipulate threads and handlers ourselves. In Android, updating a UI from a separate thread is a frequently encountered scenario.
But if it is must to show toast in doInBackGround then you can use Handler.post or runonUiThread to perform toast showing. You can't display Toast in non-UI thread (i.e Do in Background).You may try the flag concept.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With