How to display a Toast in Android AsyncTask?

走远了吗. 提交于 2019-11-27 13:14:29
Raghunandan

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

Harshal Voonna

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

@Override
protected Void doInBackground(Void... params) {
    Handler handler =  new Handler(context.getMainLooper());
    handler.post( new Runnable(){
        public void run(){
            Toast.makeText(context, "Created a server socket",Toast.LENGTH_LONG).show(); 
        }
    });
  }

This is another way which is not mentioned here as follows:

Step 1: Define Handler as global

Handler handler;

Step 2: Initialise handler in doInBackground() method as follows:

@Override
protected Void doInBackground(Void... params) {
    Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (msg.what == 1) {
           //your code
        }
    }
  };
}

Step 3: And now you can call that handler by anywhere in code by calling

if(handler != null){
  handler.sendEmptyMessage(1);
}

What more you can do is you can send data through handler as follows:

Message message = new Message();
Bundle bundle = new Bundle();
bundle.putInt("KEY", value);
message.setData(bundle);
handler.sendMessage(message);

And handle data in you handler as below

handler = new Handler(){ 
    @Override
    public void handleMessage(Message message) {
        Bundle bundle = message.getData();
        Integer value = bundle.getInt("KEY");

    }
};

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.

RAJESH KUMAR ARUMUGAM

You can't display Toast in non-UI thread (i.e Do in Background).You may try the flag concept.

public class HttpRequest extends AsyncTask<String[], Void, String> {
    boolean flag=false;
....
...
....
 @Override
    protected String doInBackground(String[]... params) {
   //set flag as true when you need to trigger the Toast
 try{
   //Some Network Calls
     } catch (HttpHostConnectException e) {
    flag=true;   
  //Triggered Flas when i got Exceptions          
       }
}
 @Override
    protected void onPostExecute(String result) {
        if(flag){
            Toast.makeText(activity, "HttpHostConnectException Occured ", Toast.LENGTH_SHORT).show();
        }


}

Happy Coding..!!!enter code here

rajpara

You are trying to display toast in non-ui thread that's why this error apear.

If you want to display toast in doInBackground method then you have to write your Toast logic inside UI thread

have a look in below answer link https://stackoverflow.com/a/11797945/582571

But it is not advisable to have a UI manipulation under non-ui thread

we can do this by passing an interface to the AsyncTask class and make a callback in onPostExecute method.

public interface IResult {
    void onSuccess(String result);
    void onError(String error);                                                  
}

public static class AsyncTaskClass extends AsyncTask<String, String, Boolean> {

    IResult iResult;

    AsyncTaskClass(IResult iResult){
        this.iResult = iResult;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        boolean result;
        try {
            //doing BackGround Operation Here
            result = true;

        } catch (Exception e) {
            Log.e(TAG,"Error: " + e.getMessage());
            result = false;
        }

       return result;
    }

    @Override
    protected void onPostExecute(Boolean success) {
        super.onPostExecute(success);
        Log.w(TAG, "On Post Execute: " + success);
        if(success)
            iResult.onSuccess("AsyncTask done successfully.");
        else
            iResult.onSuccess("Sorry! something went wrong.");

    }
}                                                                      
  IResult iResult = new IResult() {
      @Override
      public void onSuccess(String result) {
          Toast.makeText(PostActivity.this, result, Toast.LENGTH_LONG).show();
      }

      @Override
      public void onError(String error) {
          Toast.makeText(PostActivity.this, error, Toast.LENGTH_LONG).show();
      }
  };
  String param1 = "some value 1";
  String param2 = "some value 2";

  new AsyncTaskClass(iResult).execute(param1, param2);`
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!