问题描述
- android 多个Handler问题
-
新手入门求各位大牛指教。
在做一个应用时,要汇总多个数据库里的数据,因此用了多个Handler请求数据,获取到所有数据后再汇总。现在问题是怎样才能知道所有数据都请求到了?代码如下 :for (BranchVO m : response.getData()) { if(!m.isIsGroup()) ResponseBusingessEarningData(sDate,m.getBranchID(),URL); } /* * 请求营业统计数据 */ private void ResponseBusingessEarningData(String Date,String BranchID,String URL){ //封装传递参数的集合 String str="[u4e00-u9fa5]"; String localDate = Date.replaceAll(str, "-").substring(0,10); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("Date",localDate)); parameters.add(new BasicNameValuePair("BranchID",BranchID)); HttpConnectionUtil.getResponseByPost(URL, "BusinessEarning",parameters, beHandler,(BaseActivity)myContext); } ResponseHandler beHandler = new ResponseHandler(){ @Override protected void handleResponse(Message msg) { String responseText = (String) msg.getData().get("responseText"); Gson gson = new Gson(); ApiResultModel<BusinessEarningVO> response = gson.fromJson(responseText,new TypeToken<ApiResultModel<BusinessEarningVO>>(){}.getType()); if(response.getData() != null && response.getData().size() > 0){ for (BusinessEarningVO vo : response.getData()) { beList.add(vo); } beAdapter.notifyDataSetChanged(); } //dismissDialog(); } };
解决方案
CountDownLatch,类似下面这样
CountDownLatch latch=new CountDownLatch( response.getData()的数量)
for (BranchVO m : response.getData()) {
if(!m.isIsGroup()){
ResponseBusingessEarningData(sDate,m.getBranchID(),URL);
}else{
latch.countDown();//这里,不用获取数据down一次
}
}
/*
* 请求营业统计数据
*/
private void ResponseBusingessEarningData(String Date,String BranchID,String URL){
//封装传递参数的集合
String str="[u4e00-u9fa5]";
String localDate = Date.replaceAll(str, "-").substring(0,10);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("Date",localDate));
parameters.add(new BasicNameValuePair("BranchID",BranchID));
HttpConnectionUtil.getResponseByPost(URL, "BusinessEarning",parameters, beHandler,(BaseActivity)myContext);
}
ResponseHandler beHandler = new ResponseHandler(){
@Override
protected void handleResponse(Message msg) {
String responseText = (String) msg.getData().get("responseText");
Gson gson = new Gson();
ApiResultModel<BusinessEarningVO> response = gson.fromJson(responseText,new TypeToken<ApiResultModel<BusinessEarningVO>>(){}.getType());
if(response.getData() != null && response.getData().size() > 0){
for (BusinessEarningVO vo : response.getData()) {
beList.add(vo);
}
beAdapter.notifyDataSetChanged();
}
latch.countDown();//这里,完成一个down一次
//dismissDialog();
}
};
解决方案二:
简单来说就是将每个数据库对应的一个变量(自己加),然后初始化为false,处理一个置一个true,并且在置true的下一句可以去判断是否全部置为true了
时间: 2024-09-20 09:37:41