我使用自定义适配器创建了一个listView,它从数据库中获取数据并将其绑定到列表视图,适配器选择记录数量非常好,但它会一直显示所有条目的最后一条记录,例如,如果从db中检索到5条记录,列表视图将显示五次的最后一条记录。
这是代码
Activities SetAct = new Activities();
final ArrayList<Activities> sData = new ArrayList<Activities>();
try{
SQLiteDatabase db = openOrCreateDatabase("iTimeDB", MODE_PRIVATE, null);
Cursor c2 = db.rawQuery("SELECT * FROM Activities", null); // WHERE ID = '" +ID+"'"
for (c2.moveToFirst(); !c2.isAfterLast(); c2.moveToNext()) {
String title =c2.getString(c2.getColumnIndex("Title"));
String details =c2.getString(c2.getColumnIndex("Details"));
String time =c2.getString(c2.getColumnIndex("Time"));
String ref= c2.getString(c2.getColumnIndex("Ref"));
String matter =c2.getString(c2.getColumnIndex("Matter"));
String date = c2.getString(c2.getColumnIndex("Date"));
String ID = c2.getString(c2.getColumnIndex("ID"));
String IMEI1 = c2.getString(c2.getColumnIndex("IMEI"));
SetAct.setTitle(title);
SetAct.setDetails(details);
SetAct.setMatter(matter);
SetAct.setRef(ref);
SetAct.setTime(time);
SetAct.setDate(date);
SetAct.setID(ID);
sData.add(SetAct);
}
c2.close();
db.close();
}
catch(Exception e){
e.printStackTrace();
Log.v("YYY", e.toString());
}
final ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(new CustomListAdapter(this, sData));
答案 0 :(得分:2)
从外部循环下面的 循环添加 >> 循环
Activities SetAct = new Activities();
实施例
for (c2.moveToFirst(); !c2.isAfterLast(); c2.moveToNext()) {
Activities SetAct = new Activities();
String title =c2.getString(c2.getColumnIndex("Title"));
// Remaining as it is..
}
答案 1 :(得分:1)
像这样使用。
我使用以下模式来读取查询结果。
SQLiteDatabase db = new DbHelper().getWritableDatabase();
String sql = "SELECT ...";
String[] args = ...;
Cursor cs = db.rawQuery(sql, args);
while (cs.moveToNext()) {
// cs.getXxx(0), cs.getXxx(1)
}
cs.close();
db.close();
DbHelper是我从SQLiteOpenHelper
扩展的类