14

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()?

vandus
  • 3,248
  • 3
  • 30
  • 44
reiley
  • 3,759
  • 12
  • 58
  • 114
  • why you are not retuning error to onPostExecute from doInBackground() and then so this error in a toast from onPostExecute – ρяσѕρєя K Dec 09 '12 at 18:44
  • you can't modify the UI from the doInBackground() method, try to return some result, and test on that result in the onPostExecute() method , if it is , so show the Toast – Houcine Dec 09 '12 at 18:44
  • 1
    @Sam : easy man !! i didn't voted down , i've just added my comment, i know that you can give access in `doInBackground()` , but it isn't recommended to do that, if so , then why there is methods `onProgressUpdate()` and `onPostExecute()` ?? – Houcine Dec 09 '12 at 21:00
  • Consider the user here. The real answer is that you probably shouldn't be throwing a Toast in the first place. As a developer it might be nice to see updates to whatever it is you are trying to do in the background. But does your *user* really care? You are fighting the framework when you try to update the UI from `doInBackground`. – tir38 Feb 02 '15 at 00:55

9 Answers9

17

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
    }
}
Robin Chander
  • 7,225
  • 3
  • 28
  • 42
13

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.

Houcine
  • 24,001
  • 13
  • 56
  • 83
Sam
  • 86,580
  • 20
  • 181
  • 179
6

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(...)

Wicked161089
  • 481
  • 4
  • 18
Harshad07
  • 608
  • 7
  • 23
3

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

Ahmad
  • 69,608
  • 17
  • 111
  • 137
3

Create a handler object and execute all your Toast messages using that.

@Override
protected Void doInBackground(Void... params) {

    Handler handler=new handler();
    handler=  new Handler(context.getMainLooper());
    handler.post( new Runnable(){
        public void run(){
            Toast.makeText(context, "Created a server socket",Toast.LENGTH_LONG).show(); 
        }
    });
  }
Harshal Voonna
  • 349
  • 2
  • 12
1
runOnUiThread(new Runnable() {

public void run() {

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

   }
}); 

is working perfectly fine to show toast in doInBackground() method

Rasel
  • 5,488
  • 3
  • 30
  • 39
0
activity.runOnUiThread(new Runnable() {
 public void run() 
 {
    Toast.makeText(activity, "Toast teaxt", Toast.LENGTH_SHORT).show();
 }
});
Rasel
  • 5,488
  • 3
  • 30
  • 39
0

try this code

void showError(final String err) {
    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(downloadprogress.this, err + "error in download", Toast.LENGTH_LONG)
                    .show();
        }
    });
  }
Ashish Tikarye
  • 850
  • 8
  • 11
0

If you have to declare anything related to Thread, then it must be outside the runOnUiThread() method, then only it is going to execute,

    @Override
    protected String doInBackground(String... strings) {
        for(int i=0; i<10; i++) {

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(), "Example for Toast "+i, Toast.LENGTH_SHORT).show();
                }
            });

            try {
                Thread.sleep(10);
            } catch (Exception e) {}
        }

        return "";
    }
smit mehta
  • 101
  • 1
  • 4