Gan*_*vel 1 java android android-asynctask loopj asynchttpclient
我正在寻找一种方法来返回我在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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我调用代码时:
JSONParser jsonParser = new JSONParser();
jsonParser.getJSONFromUrl();
Run Code Online (Sandbox Code Playgroud)
我在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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
jsonParse.getJSONObj(new OnJSONResponseCallback(){
@Override
public void onJSONResponse(boolean success, JSONObject response){
//do something with the JSON
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13679 次 |
| 最近记录: |