Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a toast message on success callback in class

Tags:

java

android

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?

P.S 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
                }
            }
       });
like image 967
3iL Avatar asked Dec 08 '22 15:12

3iL


1 Answers

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();
like image 50
Amardeep Avatar answered Dec 27 '22 22:12

Amardeep