![](/img/trans.png)
[英]Loopj AsyncHttpResponseHandler store onSuccess response
[英]Android - loopJ AsyncHttpClient return response onFinish or 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方法完成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對象。 還有一個失敗和成功的回調。 您還可以決定請求是異步還是同步。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.