我目前正在通过 AsyncHttpClient (loopj) Web 请求请求 JsonObject,但是该请求相当慢,我需要该对象才能继续。目前,程序崩溃,因为保存的对象为空,并且在 Web 请求完成之前调用了保存函数。
这是我正在尝试执行的操作的代码 fragment :
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、让线程 hibernate 等,以及看到/尝试过这些(以及更多其他)链接,
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.?
我还尝试在注释掉代码的存储部分的同时 toast 收到的对象。 (上面评论)代码没有崩溃,但 toast 仅在 Web 请求完成一段时间后才出现。
我该如何解决这个问题? (即仅在网络请求完成后成功存储对象而不使应用程序崩溃)。我在网上搜索了很长时间,但未能找到可行的方法,而且我在 Android 方面还是个新手。
请提供帮助,如果需要更多详细信息,请告诉我。提前致谢!
最佳答案
由于您正在执行的请求是异步的,因此您应该在其完成处理程序中执行使用请求响应的逻辑。
将您的代码更改为类似的内容
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);
}
getDescription = dirDirectoryJson.get(0).getString("description").toString().trim();
setDescription( getDescription );
} catch (JSONException e) {
e.printStackTrace();
}
}
Also make your variables as instance var (that is declare them at class scope) if shows cant access non final variables within the handler
关于java - (Android | Java) AndroidAsyncHttp (Loopj) 在继续线程之前完成 Web 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37223020/