【发布时间】:2017-02-14 20:21:54
【问题描述】:
我从 asynctak 启动了 Volley JsonObject 请求,我想在完成 volley 请求后从 doinBackground 返回。我知道它在成功启动线程后从 doInBackground 返回。但是Volley Thread完成后我如何返回!
在这段代码中,我得到了 Weather 对象的空值。所有功能都正常工作。
代码:
@Override
protected JSONObject doInBackground(Void... voids) {
String url=getURL();
final JSONObject[] mJsonWeather = {null};
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
mJsonWeather[0]=response;
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("Error","can't process json result");
}
});
MySingleton.getInstance(mContext.getApplicationContext()).addToRequestQue(jsonObjectRequest);
return mJsonWeather[0];
}
@Override
protected void onPostExecute(JSONObject jsonObjectWeather) {
super.onPostExecute(jsonObjectWeather);
Weather weather = getJsonWeatherData(jsonObjectWeather);
setWeatherobj(weather);
}
【问题讨论】:
-
您确实意识到 Volley 的主要目的是消除对执行 HTTP 请求的 AsyncTask 的需求,对吧?换句话说,将 AsyncTask 完全从等式中移除
-
如果 Volley 请求
Asynctask不应该出现在图片中,也是为什么你从 Asynctask 线程调用 Volley 线程。 -
是的,但是假设我们在一个方法中进行 volley 操作,然后在完成请求之前它返回一个 null 的结果!
-
你处理来自 onResponse 的凌空结果。除此之外的任何东西都是按顺序同步运行的。异步代码很难,但理解回调很重要
标签: android android-asynctask android-volley