2017-04-01 5 views
0

Ich werde geordnete Zielinformationen aus einer Liste ausgewählter Ziele anzeigen. Zum Beispiel kann der Benutzer einige Ziele in der Liste von 10 Orten auswählen, und basierend auf der Entfernung, die die Priorität eingestellt hat, zeigt die zweite Aktivität eine berechnete Route für den Benutzer an.Android kann keine Listenansicht für eine andere Aktivität anzeigen

Der Prioritätswert jedes Ziel in einer Cloud-Datenbank gespeichert sind, und ich getestet, dass ich erfolgreich die Daten bekommen könnten. Ich werde die Daten verwenden, um die Route zu berechnen.

Es gibt keine Fehler in Logcat jedoch die geordnete Listenansicht in der zweiten Aktivität nicht angezeigt werden soll. Bitte hilf mir, es hat mich mehr als drei Tage gestört.

hier ist mein Code (erste Aktivität):

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 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 traveling time 
double travel_time; 
//long car_time; 
private int money; 
private int num = 1; 

//private SQLiteDatabase db; 
//private DestinationDBHelper dbHelper; 

private ArrayList<Integer> select_placeID = new ArrayList<Integer>(); //selected destinations 
public Map<Integer,Double> weightMap; 
public List<Plan> planList = new ArrayList<Plan>();// 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.destination_layout); 

    Bmob.initialize(this, BmobConfig.APP_ID); 

    listView = (ListView) findViewById(R.id.list_destination); 

    destinationOk_btn = (Button) findViewById(R.id.okButton); 



    initDestinations(); 


    adapter = new DestinationAdapter(destinationList, DestinationActivity.this); 
    //adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected()); 
    listView.setAdapter(adapter); 

    from_place = (TextView) findViewById(R.id.from_place); 
    date = (TextView) findViewById(R.id.date); 
    start_time = (TextView) findViewById(R.id.time); 
    end_time = (TextView) findViewById(R.id.end_time); 
    number = (TextView) findViewById(R.id.number); 
    money_view = (TextView) findViewById(R.id.request_money_et); 
    addButton = (Button) findViewById(btn_add); 
    subButton = (Button) findViewById(btn_sub); 
    backButton = (ImageView) findViewById(R.id.back); 
    telephone = (ImageView) findViewById(R.id.telephone); 
    days = (EditText) findViewById(R.id.days); 

    //listeners 
    from_place.setOnClickListener(this); 
    date.setOnClickListener(this); 
    start_time.setOnClickListener(this); 
    number.setOnClickListener(this); 
    destinationOk_btn.setOnClickListener(this); 
    addButton.setOnClickListener(this); 
    subButton.setOnClickListener(this); 
    backButton.setOnClickListener(this); 
    telephone.setOnClickListener(this); 
    end_time.setOnClickListener(this); 


    //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); 
       } 

      } 

      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(); 
       } 



       Intent intent = new Intent(); 
       intent.setClass(DestinationActivity.this, ActivityPlan.class); 

       intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList); 

       startActivity(intent); 

      } 
     } 

    }); 
    } 



//initialize the data 
private void initDestinations() { 
    Destination destination1 = new Destination("香山", R.drawable.xiangshan); 
    destinationList.add(destination1); 
    Destination destination2 = new Destination("天安门", R.drawable.car); 
    destinationList.add(destination2); 
    Destination destination3 = new Destination("后海", R.drawable.car); 
    destinationList.add(destination3); 
    Destination destination4 = new Destination("五道口", R.drawable.car); 
    destinationList.add(destination4); 
    Destination destination5 = new Destination("朝阳公园", R.drawable.car); 
    destinationList.add(destination5); 
    Destination destination6 = new Destination("雍和宫", R.drawable.car); 
    destinationList.add(destination6); 
    Destination destination7 = new Destination("八达岭长城", R.drawable.car); 
    destinationList.add(destination7); 
    Destination destination8 = new Destination("颐和园", R.drawable.car); 
    destinationList.add(destination8); 
    Destination destination9 = new Destination("三里屯", R.drawable.car); 
    destinationList.add(destination9); 
    Destination destination10 = new Destination("故宫", R.drawable.car); 
    destinationList.add(destination10); 
} 


@Override 
public void onClick(View v) { 
    //............. 
} 


//number picker 
@Override 
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { 
    Log.i("value is","" + newVal); 
} 



/** 
* 异步处理 
*/ 
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; 
    } 

    //UI 
    @Override 
    protected void onPostExecute(List<Plan> result) { 
     super.onPostExecute(result); 
     if (result != null) { 
      Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 


/** 
*plan calculation 
**/ 
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)); //以小时为单位计算旅行时长calculate total travel time 
     DecimalFormat decimalFormat = new DecimalFormat("#.0"); 
     travelTime = Double.parseDouble(decimalFormat.format(travel_time));//保留一位小数 
    } 



    //获取不同地点的priority 
    weightMap = new LinkedHashMap<Integer, Double>(); 

    int totalPriority = 0;//总优先级total priority 

    // where I am 
    final Destination start = new Destination(116.355231, 39.95222);//当前位置 


    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>();//储存每个destination的经纬度 
    /** 
    * 向后端云bmob根据id查询景点的priority 
    */ 
    new Thread (new Runnable(){ 

     @Override 
     public void run() { 
      BmobQuery<Destination> query = new BmobQuery<Destination>(); 
      for (int id : select_placeID) { 

       query.addWhereEqualTo("id", id); 

       //查询数据, 子查询 
       //query.addWhereContainedIn("id", select_placeID); 

       //返回10条数据,如果不加上这条语句,默认返回10条数据 
       //query.setLimit(10); 

       //执行查询方法 
       query.findObjects(new FindListener<Destination>() { 
        @Override 
        public void done(List<Destination> list, BmobException e) { 
         if (e == null) { 
          System.out.println("查询成功:共" + list.size() + "条数据。"); 
          for (Destination destination : list) { 
           //获得priority的信息 
           int p = destination.getPriority(); 
           //获得数据的objectId信息 
           int id = destination.getId(); 

           String name = destination.getName(); 

           //获取经纬度 
           double longitude = destination.getLongitude(); 
           double latitute = destination.getLatitute(); 

           objectMap.put(id, new Destination(longitude, latitute)); 

           //计算距离 
           double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitute(), 
             longitude, latitute); 

           pMap.put(id, p); 
           weightMap.put(id, dis); 
           nameMap.put(id, name); 

          } 
         } else { 
          Log.i("bmob", "失败:" + e.getMessage() + "," + e.getErrorCode()); 
         } 
        } 
       }); 
      } 
     } 
    }).start(); 


    //遍历整个pMap 
    for (int v : pMap.values()) { 
     totalPriority = totalPriority + v; 
    } 

    //计算weight并生成最终map 
    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(order, objectMap.get(entry.getKey()));//有哪些id,并且位置已排列好 
    } 


    PlanTask planTask = new PlanTask();//封装了每个plan计算的方法 
    //遍历map中的值,打印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); 

     //到下一个目的地需要多久开车时间 
     //按id找到destination,获取经纬度 
     double driving_time = planTask.calDrive_time(DistanceUtil.distance(
       objectMap.get(entry.getKey()).getLatitute(), 
       objectMap.get(entry.getKey()).getLongitude(), 
       objectMap.get(entry.getKey() + 1).getLatitute(), 
       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; 

} 

//验证用户输入是否完整 
public boolean validate(){ 
    //先计算旅游总时间 
    time_start = start_time.getText().toString(); 
    time_end = end_time.getText().toString(); 
    try { 
     travel_days = Integer.parseInt(days.getText().toString()); 
    } catch (NumberFormatException e) { 
     Toast.makeText(DestinationActivity.this, "游玩天数不正确", Toast.LENGTH_SHORT).show(); 
    } 


     if (StringUtils.isBlank(time_start)) { 
      Toast.makeText(DestinationActivity.this, "请输入出发时间", Toast.LENGTH_SHORT).show(); 
      return false; 
     } 

     if (StringUtils.isBlank(time_end)) { 
      Toast.makeText(DestinationActivity.this, "请输入结束时间", Toast.LENGTH_SHORT).show(); 
      return false; 
     } 

     if (travel_days <=0){ 
      Toast.makeText(DestinationActivity.this, "请输入游玩天数", Toast.LENGTH_SHORT).show(); 
      return false; 
     } 


    return true; 

} 

    } 

dies der Code der zweiten Aktivität:

public class ActivityPlan extends Activity { 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.plan_layout); 

    List<Plan> plans = new ArrayList<Plan>(); 

    Intent intent = getIntent(); 
    plans = intent.getParcelableArrayListExtra("planInfo"); 


    PlanAdapter adapter = new PlanAdapter(ActivityPlan.this, 
      R.layout.item_plan, plans); 

    ListView listView = (ListView) findViewById(R.id.plan_list); 
    listView.setAdapter(adapter); 

} 

} 

und der Code des Modellplans, die ich auf dem Display zweite Aktivität:

public class Plan implements Parcelable { 

private String place_name; 
private String arrive_time; 
private double play_time; 
private double driving_time; 


public Plan(){ 

} 

public Plan(String place_name, String arrive_time, double driving_time, double play_time) { 
    this.place_name = place_name; 
    this.arrive_time = arrive_time; 
    this.driving_time = driving_time; 
    this.play_time = play_time; 
} 

protected Plan(Parcel in) { 
    place_name = in.readString(); 
    arrive_time = in.readString(); 
    play_time = in.readDouble(); 
    driving_time = in.readLong(); 
} 


@Override 
public int describeContents() { 
    // TODO Auto-generated method stub 
    return 0; 
} 


@Override 
public void writeToParcel(Parcel dest, int flags) { 

    // TODO Auto-generated method stub 
    dest.writeString(place_name); 
    dest.writeString(arrive_time); 
    dest.writeDouble(play_time); 
    dest.writeDouble(driving_time); 
} 


public static final Creator<Plan> CREATOR = new Creator<Plan>() { 

    @Override 
    public Plan createFromParcel(Parcel source) { 
     Plan planInfo = new Plan(); 
     planInfo.place_name = source.readString(); 
     planInfo.arrive_time = source.readString(); 
     planInfo.play_time= source.readDouble(); 
     planInfo.driving_time = source.readDouble(); 

     return planInfo; 
    } 


    @Override 
    public Plan[] newArray(int size) { 
     return new Plan[size]; 
    } 
}; 

public String getPlace_name() { 
    return place_name; 
} 
public String getArrive_time() { 
    return arrive_time; 
} 
public double getPlay_time() { 
    return play_time; 
} 
public double getDriving_time() { 
    return driving_time; 
} 

public void setPlace_name(String place_name){ 
    this.place_name = place_name; 
} 

public void setArrive_time(String arrive_time){ 
    this.arrive_time = arrive_time; 
} 

public void setPlay_time(double play_time){this.play_time = play_time;} 

public void setDriving_time(double driving_time){ 
    this.driving_time = driving_time; 
} 

} 

: ich bin in Android Entwicklung, und ich fühle mich jetzt so verwirrt, 1. warum die geordnete Information nicht auf der zweiten Aktivität angezeigt werden kann, 2. wenn ich debugge, ich fand, dass die Variable "travelTime" immer 0.0 ist, und die Größe von planList, die ich verwenden werde, um die Information anzuzeigen, ist null, warum ist es?? Bitte hilf mir!! ich danke dir sehr!

+0

Sie haben übermäßigen Code geschrieben. Post freundlicherweise nur den entsprechenden Code und versuchen zu debuggen, wenn Sie auf einem Artikel in Listview sind klicken, was die Daten sind, die Sie vorbei und was Sie auf der zweiten Aktivität – Kunu

+0

ok, thx Empfang für mich –

Antwort

0

Sie AsyncTask .ArrayList Größe verwenden, ist Null, da AsyncTask Ausführung noch nicht abgeschlossen ist. Es läuft gleichzeitig im Hintergrund.

+0

zu bemerken, aber wenn ich warte auf mehr als 5 Minuten, ist die Listenansicht in der zweiten Tätigkeit noch leer, ich bin verwirrt ... –

+0

Hallo Jing Han .Wenn Sie warten, und klicken Sie auf die Asynchron Aufgabe im Hintergrund ausführt destinationOk_btn Taste, wo Sie Arraylist Größe, aber gleichzeitig nächste Aktivität öffnet – Aravindraj

+0

startActivity berechnen (neue Absicht (DestinationActivity.this, ActivityPlan.class) .putExtra ("planInfo", YOUR_ARRAYLIST)); In ActicityPlan-Klasse arraylist = (Arraylist 10) getIntent(). GetExtras(). GetSerializable ("planInfo") –

0

setzen Sie unter Linien in OnPostExecute Methode anstelle von wo Sie es jetzt setzen. .

Intent intent = new Intent(); 
      intent.setClass(DestinationActivity.this, ActivityPlan.class); 

      intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList); 

      startActivity(intent); 
+0

Ich habe das versucht, aber ich kann immer noch nicht die Listenansicht in der zweiten Aktivität sehen, es ist nur leer ... aber thx !! –

0
startActivity(new Intent(DestinationActivity.this, ActivityPlan.class).putExtra("planInfo", YOUR_ARRAYLIST)); 

In ActicityPlan Klasse

arraylist = (Arraylist<Plan>) getIntent().getExtras().getSerializable("planInfo") 
+0

Ich benutze intent.putParcelableArrayListExtra ("planInfo", (ArrayList ) planList); und intent.getParcelableArrayListExtra ("planInfo") in ActivityPlan-Klasse, ich weiß nicht, ob es einen Unterschied von Ihnen gibt? –

+0

make a wenn Prüfung vor Aktivität starten, wenn (list.size()> 0) {// Absicht} –

+0

Ich habe es, aber ich fand, dass die Liste Größe Null ist, es ist seltsam ... Ich habe planList.add (Eintrag.getKey(), Plan); Daher sollte die Array-Liste einige Elemente enthalten. Ich bin so verwirrt ... –

Verwandte Themen