简体   繁体   中英

How to call a toast message on success callback in class

I'm working on a POST API using okhttp library. Everything is working fine except I'm unable to find a way to show a simple toast message on it's success callback. How can I call a toast message to the user so he knows wether data is posted on server or not in the success and failure callbacks?

PS the code below is in a different class not in a activity class.

This is my code:

public DataSource(Context context) {
    this.mContext = context;
    mDbHelper = new DBHelper(mContext);
    mDatabase = mDbHelper.getWritableDatabase();
}



    post(URL, jsonData, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("FAILED", "onFailure: Failed to upload data to server");
                //here I want to show toast message
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {

                    Log.i("SUCCESSFUL", "onSuccess: data uploaded");

                    //here I want to show toast message

                } else {
                    Log.i("UN SUCCESSFUL", "onFailure: Failed to upload data to server");
                    //here I want to show toast message
                }
            }
       });

Every app has its own special thread that runs UI objects such as View objects; this thread is called the UI thread. Only objects running on the UI thread have access to other objects on that thread. Because tasks that you run on a thread from a thread pool aren't running on your UI thread, they don't have access to UI objects. To move data from a background thread to the UI thread, use a Handler that's running on the UI thread or can use android implementation for the same as shown here.

- Case 1

 MyActivity.this.runOnUiThread(new Runnable() {
            @Override
            void run() {
               Toast.makeText(MyActivity.this,
                    "message", Toast.LENGTH_LONG).show();
            });

- Case 2

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
       Toast.makeText(MyActivity.this,
                    "message", Toast.LENGTH_LONG).show();
    }
});

Had it been Main thread you would have used it directly like

Toast.makeText(MyActivity.this,
                    "message", Toast.LENGTH_LONG).show();

This callback is an asynchronous function, and you can change View just in UI-thread, so Handler will be helpd for you.

    ....
    private final static int MSG_SUCCESS = 0x0001;
    private final static int MSG_FAIL = 0x0002;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
              case MSG_SUCCESS:
                 //Toast success
                  break;
              case MSG_FAIL:
                 //Toast fail
                  break;
              default:
                  break;
            }
        }
    };

    ......
    ......

    if (response.isSuccessful()) {
              Log.i("SUCCESSFUL", "onSuccess: data uploaded");
              handler.sendEmptyMessage(MSG_SUCCESS);
           } else {
             Log.i("UN SUCCESSFUL", "onFailure: Failed to upload data to server");
              handler.sendEmptyMessage(MSG_FAIL);
            }
     ......

You are getting error

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Because you're calling it from a worker thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread. You could use a handler,

 @Override
 public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {    
                    Log.i("SUCCESSFUL", "onSuccess: data uploaded");

                    context.runOnUiThread(new Runnable() {
                    public void run() {
                    Toast.makeText(context, "SUCCESSFUL", Toast.LENGTH_SHORT).show();
                     }
                  });
                }

Try this

Toast.makeText(YourActivity.this, "Your Message", Toast.LENGTH_SHORT).show();

Activity

post(URL, jsonData, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i("FAILED", "onFailure: Failed to upload data to server");
                        //here I want to show toast message
                        Toast.makeText(YourActivity.this, "Your Message", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()) {

                            Log.i("SUCCESSFUL", "onSuccess: data uploaded");

                            //here I want to show toast message
                            Toast.makeText(YourActivity.this, "Your Message", Toast.LENGTH_SHORT).show();

                        } else {
                            Log.i("UN SUCCESSFUL", "onFailure: Failed to upload data to server");
                            //here I want to show toast message
                            Toast.makeText(YourActivity.this, "Your Message", Toast.LENGTH_SHORT).show();
                        }
                    }
   });

Fragment

post(URL, jsonData, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i("FAILED", "onFailure: Failed to upload data to server");
                        //here I want to show toast message
                        Toast.makeText(getActivity(), "Your Message", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()) {

                            Log.i("SUCCESSFUL", "onSuccess: data uploaded");

                            //here I want to show toast message
                            Toast.makeText(getActivity(), "Your Message", Toast.LENGTH_SHORT).show();

                        } else {
                            Log.i("UN SUCCESSFUL", "onFailure: Failed to upload data to server");
                            //here I want to show toast message
                            Toast.makeText(getActivity(), "Your Message", Toast.LENGTH_SHORT).show();
                        }
                    }
   });

Edit

Handler handler = new Handler();

handler.runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(mContext, "Your Message", Toast.LENGTH_SHORT).show();
  }
});

Try this

TaskActivity.this.runOnUiThread(new Runnable() {
        @Override
        void run() {
            Toast msg = Toast.makeText(TaskActivity.this,
                "message", Toast.LENGTH_LONG);
            msg.show();
        });

Just send the context of your activity while calling this method:

void methodName(Context c){

 post(URL, jsonData, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.i("FAILED", "onFailure: Failed to upload data to server");
                    //here I want to show toast message
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {

                        Log.i("SUCCESSFUL", "onSuccess: data uploaded");
                       Toast.makeText(c,"message",Toast.LENGTH_SHORT).show();
                        //here I want to show toast message

                    } else {
                        Log.i("UN SUCCESSFUL", "onFailure: Failed to upload data to server");
                        //here I want to show toast message
                    }
                }
});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM