Android - loopJ AsyncHttpClient return response onFinish or onSuccess

非 Y 不嫁゛ 提交于 2019-11-29 02:46:31

Use an interface. This way you can create your own callback whose methods can be called from onSuccess or onFailure.

public interface OnJSONResponseCallback {
    public void onJSONResponse(boolean success, JSONObject response);
}

public JSONObject getJSONObj(OnJSONResponseCallback callback) {
    ...
   @Override
   public void onSuccess(int i, Header[] headers, String response) {
       try {
           jObj = new JSONObject(response);
           callback.onJSONResponse(true, jObj);
       } catch (JSONException e) {
           Log.e("Exception", "JSONException " + e.toString());
       }
   }

   @Override
   public void onFailure(int statusCode, Header[] headers, String response, Throwable e) {
       try {
           jObj = new JSONObject(response);
           callback.onJSONResponse(false, jObj);
       } catch (JSONException e) {
           Log.e("Exception", "JSONException " + e.toString());
       }
   }
}

And to call it:

jsonParse.getJSONObj(new OnJSONResponseCallback(){
    @Override
    public void onJSONResponse(boolean success, JSONObject response){
       //do something with the JSON
    }
});

Use retrofit. It manages the http request very good and converts the json objects automatically to your Java objects. There is also a failure and success Callback. You can also decide whether the request is async or sync.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!