I think you want to do something like this:
public class MyActivity extends Activity implements Callback , View.OnClickListener { @Override public void onCreate(Bundle savedState) { super.onCreate(savedState); findViewById(R.id.DoHttp).setOnClickListener(this); } @Override public void onClick(View v) { if (v.getId(() == R.id.DoHttp) { OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build(); okHttpClient.newCall(request).enqueue(this); } } @Override public void onFailure(Request request, IOException e) {
In the above exercise, we implement a callback, and then when we create the okhttp request, we pass it an instance of our (this), and so we can get oktthp to call the class, we could make the inner class just as easy, but it reduces the number of classes we need to do. I used the button to illustrate when the Http call was made, but it can happen another time, for example, it can happen when the screen is first created (in onCreate). Be careful when turning the screen. It also assumes that the callback is executed in the main thread, which I think will be, but I'm not sure, since I use okttp differently than you do. If it does not return the results of the response in the main thread, you can call runOnUiThread () and pass Runnable to it, which does the job of updating the views.
source share