我必须回应截击请求的结果。但因为它是异步的。在继续之前我需要等待结果。如果我没有,我会得到nullobjects。
如何设置标志并等待标志关闭。
categoryslashid = new JSONObject[Category_IDs.size()];//size of the list containing all categories
taskfinished = new boolean[Category_IDs.size()];
//boolean is initialized to false
//Request to category/{id} to get
for(int i= 0;i<Category_IDs.size();i++)
{ makevolleyrequesforCategorySlashID(Const.URL_FULL_STOREURL+Const.URL_PRODUCT_GET_CATEGORY_ID,i);
}
public void makevolleyrequesforCategorySlashID(URL,id)
{
//volley implementation
public void onResponseoverride
{
categoryslashid[i]=response;
taskfinished[i]=true;
}
}
现在我必须在完成所有布尔任务完成后才能继续。
public boolean areAllTrue()
{
for(boolean b : taskfinished) if(!b) return false;
return true;
}
答案 0 :(得分:4)
实现一个接口,并在数据准备好后使用它回调。像这样:
public interface OnDownloadTaskCompleted {
public void onTaskCompleted(List<ofSomething> list, boolean error, String message);
}
然后,您应该将此实例传递给您的请求并覆盖onTaskCompleted()
private void downloadData(){
final DownloadUsingVolley downloader = new DownloadUsingVolley(getActivity());
downloader.retrieveData(new OnDownloadTaskCompleted() {
@Override
public void onTaskCompleted(List<ofSomething> list, boolean error, String message) {
//do something with your data
}
});
}
我假设你有一个类,你实现了凌空的东西(DownloadusingVolley),一个方法会调用它并自己发出请求(retrieveData)。
retrieveData可以像这样实现:
private void retrieveData(String url, final OnDownloadTaskCompleted taskCompleted){
final JsonObjectRequest request = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>(){
@Override
public void onResponse(JSONObject response) {
try {
//parse
taskCompleted.onTaskCompleted(result,false,null);
}catch (JSONException e){
taskCompleted.onTaskCompleted(0,true,e.getMessage());
}
}
},new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError volleyError) {
taskCompleted.onTaskCompleted(0,true,volleyError.getMessage());
}
});
//adding request into the queue
ApplicationClass.getInstance().addToRequestQueue(request,"aTag");
}
在这里你可以找到关于凌空的好教程: Asynchronous HTTP Requests in Android Using Volley