我正在寻找一种方法来返回我在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方法完成http帖子之前得到了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 对象。还有一个失败和成功回调。您还可以决定请求是异步还是同步。