gpt4 book ai didi

android - SQLite 选择所有行并添加到 ListView Android

转载 作者:行者123 更新时间:2023-11-29 17:38:33 25 4
gpt4 key购买 nike

我想将从数据库中检索到的每一行添加到 ListView 中,这是我目前所做的。

Activity 类代码

    private void getList() {
list.add(dbms.selectAllFromRatings());
arrayAdapter = new ArrayAdapter<String>(StationListView.this,
android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}

//来自 databaseHelper 类的代码

    public String selectAllFromRatings() {
String selectAllQuery = " SELECT * FROM " + RATING_TABLE_NAME ;
SQLiteDatabase sql = this.getReadableDatabase();
Cursor c = sql.rawQuery(selectAllQuery, null);
c.moveToFirst();
return c.getString(c.getColumnIndex("stationName1"));
}

最佳答案

那样你只会得到一个元素。您需要返回一个 List。遍历 Cursor 按顺序添加每个元素,直到没有更多元素,完成后关闭它。例如:

private void getList() {
List<String> list = dbms.selectAllFromRatings();
arrayAdapter = new ArrayAdapter<String>(StationListView.this,
android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}

// Since getList() is private, this method should also be private
private List<String> selectAllFromRatings() {
String selectAllQuery = " SELECT * FROM " + RATING_TABLE_NAME;
SQLiteDatabase sql = this.getReadableDatabase();
Cursor c = sql.rawQuery(selectAllQuery, null);
final List<String> list = new ArrayList<String>();
try {
while(c.moveToNext()) {
list.add(c.getString(c.getColumnIndex("stationName1")));
}
} finally {
c.close();
}
return list;
}

请注意,我没有对此进行测试,但它应该会让您了解如何循环游标结果。

关于android - SQLite 选择所有行并添加到 ListView Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29610574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com