I created a helper class to handle all of my HTTP calls in my application. This is a simple singleton shell for okhttp that looks like this (I omitted some non-essential parts):
public class HttpUtil { private OkHttpClient client; private Request.Builder builder; ... public void get(String url, HttpCallback cb) { call("GET", url, cb); } public void post(String url, HttpCallback cb) { call("POST", url, cb); } private void call(String method, String url, final HttpCallback cb) { Request request = builder.url(url).method(method, method.equals("GET") ? null : new RequestBody() {
Then in my main action I use this helper class:
HttpUtil.get(url, new HttpUtil.HttpCallback() { @Override public void onFailure(Response response, Throwable throwable) {
onSuccess throws an exception when running the code:
android.view.ViewRootImpl $ CalledFromWrongThreadException: only the original thread that created the view hierarchy can touch its views.
From my point of view, Okhttp callbacks work in the main thread, so why can I get this error?
** Like the note, I created the HttpCallback interface for the Okhttp Callback class shell because I wanted to change the behavior of onResponse and onFailure so that I could combine the logic of processing failed responses due to i / o exceptions and failed responses due to server problems .
Thank.
Michael Jun 16 '14 at 15:07 2014-06-16 15:07
source share