Android – loopJ AsyncHttpClient返回响应onFinish或onSuccess

我正在寻找一种方法来返回我在loopJ AsyncHttpClient onFinish或onSuccess或onFailure中得到的响应。 截至目前,我有这段代码:

**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; } } 

当我调用代码时:

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

我在onSuccess或onFailure方法完成httppost之前得到了JSONException

我注意到,在第一次调用时:Log.e(“Exception”,“JSONException”+ e.toString()); 正在记录,然后Log.d(“onSuccess:”,jsonString); 记录值,因为它们处于同步状态。

在第二次调用:jObj = new JSONObject(jsonString); 成功执行并获得该方法的所需返回值,因为到那时onSuccess方法已经将值赋给变量jsonString。

现在我正在寻找的是一种防止jObj从方法中过早返回的方法。

反正有没有制作方法getJSONObj,等待完成AsyncHttpClient任务,将变量赋值给jsonString,创建JSONObject并返回它?

提前致谢! 干杯!

使用界面。 这样您就可以创建自己的回调,其方法可以从onSuccess或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()); } } } 

并称之为:

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

使用改造 。 它非常好地管理http请求,并自动将json对象转换为Java对象。 还有失败和成功的回调。 您还可以决定请求是异步还是同步。