我目前通過AsyncHttpClient(loopj)web請求請求JsonObject,但是請求速度很慢,我需要該對象繼續。目前該程序因爲保存的對象爲空而崩潰,並且在Web請求完成之前調用save函數。(Android | Java)AndroidAsyncHttp(Loopj)在繼續線程之前完成Web請求
這裏是我的什麼,我試圖做的代碼片段:
btnCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncHttpClient client = new AsyncHttpClient();
String apiAddress = MYAPIADDRESS;
client.get(apiAddress,
new JsonHttpResponseHandler() {
//@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
JSONObject tempTransition = response.getJSONArray("items").getJSONObject(0).getJSONObject("snippet");
Toast.makeText(getApplicationContext(), tempTransition.get("description").toString(), Toast.LENGTH_SHORT).show();
if(!dirDirectoryJson.contains(tempTransition)){
dirDirectoryJson.add(tempTransition);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
}
@Override
public void onFinish() {
// Completed the request (either success or failure)
}
});
//*** Crashes here ****
//dirDirectoryJson returning null object from above due to call before complete web request and crashes the program
try {
getDescription = dirDirectoryJson.get(0).getString("description").toString().trim();
setDescription(getDescription);
} catch (JSONException e) {
e.printStackTrace();
}
}
我試過SyncHttpClient,使線程休眠等,以及看到/嘗試這些(以及更多其它)鏈接,
How to wait for async http to end before continuing?
https://forum.qt.io/topic/5389/how-to-ensure-fully-asynchronous-web-requests
How to wait for all requests to finish
How to make the Main thread wait, when i dont know when will Async task finish the job.?
我也嘗試在註釋掉代碼的存儲部分時收到的對象。 (註釋見上文)代碼沒有崩潰,但只有在Web請求完成後纔會出現Toast。
我該如何着手解決這個問題? (即,在web請求完成之後,成功存儲對象而不會使應用程序崩潰只有)。我一直在網上搜索很長時間,但沒有得到一個可行的方法,我在Android有點新手。
如果需要更多的細節請做好心的幫助並告訴我。提前致謝!
這是保存功能? – Shubhank
@Shubhank嗨!在上面的代碼中,我已經在上面的代碼中進行了評論。它在存儲之前崩潰,甚至在達到保存之前:'(我已經完成了編輯,輸入錯誤 – Candiie
請在成功移動代碼 – Shubhank