1

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:

**jsonParse.java file**
public class jsonParse {
    static JSONObject jObj = null;
    static String jsonString = "";
    AsyncHttpClient client;

      public JSONObject getJSONObj() {
            RequestParams params;
            params = new RequestParams();
            params.add("username", "user");
            params.add("password", "password");
            client = new AsyncHttpClient();
            client.post("http://example.com", params, new TextHttpResponseHandler() {

                @Override
                public void onSuccess(int i, Header[] headers, String response) {
                    jsonString = response;
                    Log.d("onSuccess: ", jsonString);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String response, Throwable e) {
                    if (statusCode == 401) {
                        jsonString = response;
                        Log.d("onFailure: ", jsonString);
                    }
                }

            });
            try {
                jObj = new JSONObject(jsonString);
            } catch (JSONException e) {
                Log.e("Exception", "JSONException " + e.toString());
            }
            return jObj;
        }
}

When I invoke the code:

JSONParser jsonParser = new JSONParser();
jsonParser.getJSONFromUrl(); 

I get the JSONException before onSuccess or onFailure method finishes the http post.

I have noticed that, on the first invoke: Log.e("Exception", "JSONException " + e.toString()); is getting logged and then Log.d("onSuccess: ", jsonString); logs the value as they are in the sync state.

On the second invoke: jObj = new JSONObject(jsonString); gets executed successfully and I get desired return value for the method, because by that time onSuccess method would have already assigned the value to the variable jsonString.

Now what I am exactly looking for is a way to prevent premature return of jObj from the method.

Is there anyway to make the method, getJSONObj, wait for the completion of AsyncHttpClient task, assign the variable into jsonString, create the JSONObject and return it?

Thanks in advance! Cheers!

Ganesh Rathinavel
  • 1,243
  • 4
  • 17
  • 38

2 Answers2

7

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
    }
});
JstnPwll
  • 8,585
  • 2
  • 33
  • 56
  • thanks! I am really a newbie to android and java development. Can I have a reference url to such an example? Cheers :) – Ganesh Rathinavel Nov 14 '14 at 20:38
  • @justine powell I followed your code and I got an exception. Would you please mind going through the exception? http://pastebin.com/gHwzdhxa ps: I have declared the variable on the top: **OnJSONResponseCallback callback**; The line `callback.onJSONResponse(false, jObj);` is reason behind this exception. any ideas? :) – Ganesh Rathinavel Nov 14 '14 at 21:20
  • 1
    It means your callback is null here. You shouldn't define the callback here, you should define it from wherever you call getJSONObj (as I showed as an example in my answer). – JstnPwll Nov 14 '14 at 21:32
  • 1
    man!! you are super awesome! exactly what I wanted! :) well i learned a thing or two today! Good day, Sir! – Ganesh Rathinavel Nov 14 '14 at 21:38
1

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.

mapodev
  • 988
  • 8
  • 14