这个问题困扰了我很长时间.我使用名为bmob的云数据库,发现可以成功获取所需的数据.但是,循环中可能会有一些错误,我只能获取最后选择的项目的信息.
附:我使用一个称为“播放列表”的数组列表来存储计算的数据,该数据将用于在下一个活动中显示列表视图.
这是我的代码:
public class DestinationActivity extends Activity implements OnClickListener, NumberPicker.OnValuechangelistener {private TextVIEw from_place, date, days, start_time, end_time, number, money_vIEw;private button addbutton, subbutton;private ImageVIEw backbutton, telephone;private ListVIEw ListVIEw;private button destinationOk_btn;private ShapeLoadingDialog shapeLoadingDialog;private Tip startTip;private Calendar calendar;private DatePickerDialog dialog;private TimePickerDialog dialog2;private List<Destination> destinationList = new ArrayList<Destination>();private DestinationAdapter adapter;private int number_value = 1; private String time_start;private String time_end;private int travel_days;double travelTime;//total playing timedouble travel_time;private int money;private int num = 1;private ArrayList<Integer> select_placeID = new ArrayList<Integer>(); public Map<Integer,Double> weightmap;public List<Plan> planList = new ArrayList<Plan>();int[] selectedID = new int[10];@OverrIDeprotected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.destination_layout); //initialize the cloud database Bmob.initialize(this, BmobConfig.APP_ID); ListVIEw = (ListVIEw) findVIEwByID(R.ID.List_destination); destinationOk_btn = (button) findVIEwByID(R.ID.okbutton); initDestinations(); // initialize the data adapter = new DestinationAdapter(destinationList, DestinationActivity.this); //adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected()); ListVIEw.setAdapter(adapter); //....Listeners and textvIEws....... //submit button destinationOk_btn.setonClickListener(new OnClickListener() { @OverrIDe public voID onClick(VIEw v) { select_placeID.clear(); for (int i = 0; i < destinationList.size(); i++) { if (DestinationAdapter.getIsSelected().get(i)) { select_placeID.add((i + 1)); } } //change to int array selectedID = new int[select_placeID.size()]; for(int i = 0;i<select_placeID.size();i++){ selectedID[i] = select_placeID.get(i); } if (select_placeID.size() == 0) { AlertDialog.Builder builder1 = new AlertDialog.Builder(DestinationActivity.this); builder1.setMessage("no records"); builder1.show(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(DestinationActivity.this); builder.setMessage("waiting for magic..."); builder.show(); /** * calculate the route */ if (valIDate()) { new calRoute().execute(); } } } });}//initialize the dataprivate voID initDestinations() { //........}@OverrIDepublic voID onClick(VIEw v) { //.......}/** * asynctask */private class calRoute extends AsyncTask<VoID, VoID, List<Plan>>{ public calRoute(){ // Todo auto-generated constructor stub } @OverrIDe protected List<Plan> doInBackground(VoID... params) { List<Plan> result = calculate(time_start, time_end, travel_days); return result; } @OverrIDe protected voID onPostExecute(List<Plan> result) { super.onPostExecute(result); if (result != null) { Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show(); if(planList.size() > 0) { Intent intent = new Intent(); intent.setClass(DestinationActivity.this, ActivityPlan.class); intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList); startActivity(intent); } else{ Toast.makeText(DestinationActivity.this, "no plan", Toast.LENGTH_SHORT).show(); } } }}/** *plan **/public List<Plan> calculate(String time_start, String time_end, int travel_days) { SimpleDateFormat df = new SimpleDateFormat(("HH:mm")); Date starttime = new Date(); Date endtime = new Date(); try { starttime = df.parse(time_start); } catch (ParseException e) { e.printstacktrace(); } try { endtime = df.parse(time_end); } catch (ParseException e) { e.printstacktrace(); } double l = endtime.getTime() - starttime.getTime(); double hour = (l / (60 * 60 * 1000)); double min = ((l / (60 * 1000)) - hour * 60); if(min == 0){ min = 60; } else { travel_time = ((1.0 * travel_days * hour) * (min / 60)); DecimalFormat decimalFormat = new DecimalFormat("#.0"); travelTime = Double.parseDouble(decimalFormat.format(travel_time)); } weightmap = new linkedHashMap<Integer, Double>(); //store weight int totalPriority = 0;//total priority final Destination start = new Destination(116.32133, 39.92269); final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>(); final HashMap<Integer, String> nameMap = new HashMap<Integer, String>(); final HashMap<Integer, Destination> objectMap = new linkedHashMap<Integer, Destination>(); /** * get the data from cloud database */ Bmobquery<Destination> query = new Bmobquery<Destination>(); for (int sID: selectedID) { query.adDWhereEqualTo("ID", sID); query.findobjects(new FindListener<Destination>() { @OverrIDe public voID done(List<Destination> List, BmobException e) { if (e == null) { System.out.println("success:total" + List.size() + "items."); for (Destination destination : List) { int p = destination.getPriority(); int ID = destination.getID(); String name = destination.getname(); double longitude = destination.getLongitude(); double latitude = destination.getLatitude(); objectMap.put(ID, new Destination(longitude, latitude)); System.out.println(ID); double dis = distanceUtil.distance(start.getLongitude(), start.getLatitude(), longitude, latitude); pMap.put(ID, p); weightmap.put(ID, new Double(dis)); nameMap.put(ID, name); } } else { Log.i("bmob", "error:" + e.getMessage() + "," + e.getErrorCode()); } } }); } for (Integer key : pMap.keySet()) { int p = pMap.get(key).intValue(); totalPriority = totalPriority + p; } double weight = 0.0; for (Map.Entry<Integer, Double> hm : weightmap.entrySet()) { double hm2Value = pMap.get(hm.getKey()); weight = totalPriority / hm.getValue() * hm2Value; weightmap.put(hm.getKey(), weight); } /** * 按照weight值来排序 * 判断是否传递数据给plan_activity */ MapUtil.sortByValue(weightmap); //排好序后计算距离 Iterator it = weightmap.entrySet().iterator(); int order = 0; while (it.hasNext()) { order++; Map.Entry entry = (Map.Entry) it.next(); objectMap.put(new Integer(order), objectMap.get(entry.getKey())); } PlanTask planTask = new PlanTask();//封装了每个plan计算的方法 for (Map.Entry<Integer, Double> entry : weightmap.entrySet()) { System.out.println("ID= " + entry.getKey()); double play_time = planTask.calPlay_time(weightmap.size(), weightmap.get(entry.getKey()), travelTime); double driving_time = planTask.calDrive_time(distanceUtil.distance( objectMap.get(entry.getKey()).getLatitude(), objectMap.get(entry.getKey()).getLongitude(), objectMap.get(entry.getKey() + 1).getLatitude(), objectMap.get(entry.getKey() + 1).getLongitude() )); String arrive_time = "hello world";//未完待续 String place_name = nameMap.get(entry.getKey()); Plan plan = new Plan(place_name, arrive_time, driving_time, play_time); //传递plan对象List planList.add(entry.getKey(), plan); } return planList;}
}
当我调试它时,我发现在calculate()函数中,
Bmobquery<Destination> query = new Bmobquery<Destination>(); for (int sID: selectedID) { query.adDWhereEqualTo("ID", sID);query.findobjects(new FindListener<Destination>() { @OverrIDe public voID done(List<Destination> List, BmobException e) { if (e == null) { System.out.println("success:total" + List.size() + "items."); for (Destination destination : List) { int p = destination.getPriority(); int ID = destination.getID(); String name = destination.getname(); double longitude = destination.getLongitude(); double latitude = destination.getLatitude(); objectMap.put(ID, new Destination(longitude, latitude)); System.out.println(ID); //calculate the distance double dis = distanceUtil.distance(start.getLongitude(), start.getLatitude(), longitude, latitude); pMap.put(ID, p); weightmap.put(ID, new Double(dis)); nameMap.put(ID, name); } } else { Log.i("bmob", "error:" + e.getMessage() + "," + e.getErrorCode()); } } });
为“成功:总共1个项目”.循环后,如果我选择了3个项目,则将是“成功:总共1个项目”. 3次,仅捕获最后一项的信息.
AND三个哈希图的大小:pMap,nameMap和objectMap均为零.为什么???真奇怪
LogCAT中没有错误,但是,有序列表视图无法显示在第二个活动中.请帮助我,它困扰了我很长时间.
谢谢!!!
解决方法:
不幸的是,我无法弄清楚,因为我对反应式编程并不十分满意,因为该平台通常会使用很多rxjava,但这可以使代码有所增强
final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();final HashMap<Integer, Destination> objectMap = new linkedHashMap<Integer, Destination>();/** * get the data from cloud database */Bmobquery<Destination> query = new Bmobquery<Destination>();// this time only one List of three elements is added instead of three Lists of one element eachquery.adDWhereContainedIn("ID", Arrays.asList(selectedID));query.findobjects(new FindListener<Destination>() { @OverrIDe public voID done(List<Destination> List, BmobException e) { if (e == null) { System.out.println("success:total" + List.size() + "items."); for (Destination destination : List) { int p = destination.getPriority(); int ID = destination.getID(); String name = destination.getname(); double longitude = destination.getLongitude(); double latitude = destination.getLatitude(); objectMap.put(ID, new Destination(longitude, latitude)); System.out.println(ID); //calculate the distance double dis = distanceUtil.distance(start.getLongitude(), start.getLatitude(), longitude, latitude); pMap.put(ID, p); weightmap.put(ID, new Double(dis)); nameMap.put(ID, name); } // continue execution here though you won't be able to return a List of plans here } else { Log.i("bmob", "error:" + e.getMessage() + "," + e.getErrorCode()); } }});
希望这可以帮助 :)
总结以上是内存溢出为你收集整理的循环有问题,无法将值放入hashmap中全部内容,希望文章能够帮你解决循环有问题,无法将值放入hashmap中所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)