【发布时间】:2016-05-15 04:12:57
【问题描述】:
我目前正在通过 AsyncHttpClient (loopj) Web 请求请求 JsonObject,但是请求相当慢,我需要该对象才能继续。目前程序崩溃,因为要保存的对象是空的,并且在 Web 请求完成之前调用了保存函数。
这是我正在尝试做的代码的 sn-p:
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.?
我还尝试在注释掉代码的存储部分时为收到的对象敬酒。 (上面有评论)代码没有崩溃,但吐司只在网络请求完成后出现。
我该如何解决这个问题? (即在网络请求完成后仅成功存储对象而不会导致应用程序崩溃)。我在网上搜索了很长时间,但没有找到可行的方法,而且我还是 Android 的新手。
请提供帮助,如果需要更多详细信息,请告诉我。提前致谢!
【问题讨论】:
-
保存功能是什么?
-
@Shubhank 你好!实际上,在最后一次尝试捕获中,我已经在上面的代码中发表了评论。它甚至在到达保存之前就在存储中崩溃了:'(我已经完成了编辑,抱歉打错了。
-
请在成功时也移动该代码
-
@Shubhank 嗨,我试过了,它说我的变量 getDescription 和 setDescription 必须声明为 final 但我不能将它们声明为 final。
-
将它们声明为实例变量然后@Candiie
标签: java android android-async-http loopj