我将从所选目的地列表中显示有序目的地信息。例如,用户可以在10个地方的列表中选择一些目的地,并根据我设置的优先级的距离,第二个活动将显示用户的计算路线。
每个目的地的优先级值都存储在云数据库中,我测试过我可以成功获取数据。我将使用这些数据来计算路线。
LogCAT中没有错误,但是,有序列表视图无法显示在第二个活动中。请帮助我,它困扰了我超过三天。
这是我的代码(第一个活动):
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;
}
}
这是第二项活动的代码:
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);
}
}
和模型Plan的代码,我将在第二个活动中显示:
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;
}
}
我是Android开发的新手,现在我感到很困惑, 1.为什么有序信息无法显示在第二个活动上,2。当我调试时,我发现变量&#34; travelTime&#34;总是0.0,我将用来显示信息的planList的大小为零,为什么呢?请帮我!!非常感谢你!
答案 0 :(得分:0)
您正在使用AsyncTask .ArrayList大小为零,因为AsyncTask尚未完成执行。它同时在后台运行。
答案 1 :(得分:0)
将下面的行放在OnPostExecute方法中,而不是现在放在哪里。 。
Intent intent = new Intent();
intent.setClass(DestinationActivity.this, ActivityPlan.class);
intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);
startActivity(intent);
答案 2 :(得分:0)
startActivity(new Intent(DestinationActivity.this, ActivityPlan.class).putExtra("planInfo", YOUR_ARRAYLIST));
在ActicityPlan类
arraylist = (Arraylist<Plan>) getIntent().getExtras().getSerializable("planInfo")