我有以下代码和下面描述的问题,带有一个arraylist:
class WP{
double id, type;
String shortname, name;
}
public class GPSAct extends Activity {
...
public ArrayList<WP> waypoints = new ArrayList<WP>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
getData(where);
for(int i=0;i<waypoints.size();i++){
Toast.makeText(getApplicationContext(), waypoints.get(i).shortname, Toast.LENGTH_LONG).show();
}
}
public void getData(String where) {
WP wps = new WP();
try {
openDataBase();
Cursor cur = myDataBase.query(TABLE_WP, null, where, null, null, null, null);
cur.moveToFirst();
waypoints.clear();
for (int i = 0; i < cur.getCount(); i++) {
wps.id = cur.getDouble(0);
wps.type = cur.getDouble(0);
wps.shortname = cur.getString(1);
wps.name = cur.getString(2);
waypoints.add(i, wps);
}
cur.close();
...
问题是,当我尝试访问路径点arraylist(使用waypoints.get(i),其中我从0开始直到waypoints.size()),数组的所有元素都具有相同的值(值在getData()中添加的最后一个wps元素。
答案 0 :(得分:2)
这里有两个问题。
new Wp()
,这样列表中的每个元素都不会指向同一个东西。这样的事情:
do {
wps = new Wp();
wps.id = cur.getDouble(0);
wps.type = cur.getDouble(0);
wps.shortname = cur.getString(1);
wps.name = cur.getString(2);
waypoints.add(i, wps);
} while(cur.moveToNext());