Android - loopJ AsyncHttpClient return response onFinish or onSuccess

前端 未结 2 771
小蘑菇
小蘑菇 2020-12-15 14:34

I am looking for a way to return the response I get in loopJ AsyncHttpClient onFinish or onSuccess or onFailure. As of now I have this piece of code:

**jsonP         


        
相关标签:
2条回答
  • 2020-12-15 15:17

    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
        }
    });
    
    0 讨论(0)
  • 2020-12-15 15:38

    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.

    0 讨论(0)
提交回复
热议问题