Skip to content Skip to sidebar Skip to footer

Okhttp Update Ui From Enqueue Callback

I am trying to use OkHTTP library. When making a call to the server and getting a successful response back. i need to update the UI. How can this be done when doing an Async call u

Solution 1:

You can refer to the following sample code, hope this helps!

publicclassMainActivityextendsAppCompatActivity {
    privatestaticfinalStringLOG_TAG="OkHttp";
    private TextView mTextView;
    private Handler mHandler;
    private String mMessage;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.textView);
        mHandler = newHandler(Looper.getMainLooper());
        OkHttpClientclient=newOkHttpClient();
        // GET requestRequestrequest=newRequest.Builder()
                .url("http://...")
                .build();
        client.newCall(request).enqueue(newCallback() {
            @OverridepublicvoidonFailure(Request request, IOException e) {
                mMessage = e.toString();
                Log.e(LOG_TAG, mMessage); // no need inside run()
                mHandler.post(newRunnable() {
                    @Overridepublicvoidrun() {
                        mTextView.setText(mMessage); // must be inside run()
                    }
                });
            }

            @OverridepublicvoidonResponse(Response response)throws IOException {
                mMessage = response.toString();
                Log.i(LOG_TAG, mMessage); // no need inside run()
                mHandler.post(newRunnable() {
                    @Overridepublicvoidrun() {
                        mTextView.setText(mMessage); // must be inside run()
                    }
                });
            }
        });
    }
}

Solution 2:

If your code doesn't update the UI, I would suggest you to specify the thread, since UI is on its own thread:

client.newCall(request).enqueue(new Callback() {

    @Override
    public void onFailure(Request request, IOException e) {

    }

    @Override
    public void onResponse(Response response) throws IOException {

        if (response.isSuccessful()) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    //TODO: update your UI
                }

            });
        } 
    }
});

Solution 3:

Try this:

HandlermainHandler=newHandler(Looper.getMainLooper());
mainHandler.post(newRunnable() {
    @Overridepublicvoidrun() {
        // code to interact with UI
    }
});

Solution 4:

For the sake of having a clean code, I would suggest you not to put your entire code inside the runnable.

A simple example:

publicclassMainActivityextendsAppCompatActivity {

    protectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        OkHttpClientclient=newOkHttpClient();
        Requestrequest=newRequest.Builder()
            .url("http://...").build();

        client.newCall(request).enqueue(newCallback() {


            @OverridepublicvoidonFailure(Request request, IOException e) {
                e.printStackTrace();
            }


            @OverridepublicvoidonResponse(Response response)throws IOException {

                finalStringbody= response.body().string();
                runOnUiThread(newRunnable() {
                    @Overridepublicvoidrun() {
                        updateUI(body);
                    }
                });

            }


        });
    }

    privatevoidupdateUI(responseBody){
        //TODO: update your UI
    }

}

Post a Comment for "Okhttp Update Ui From Enqueue Callback"