gpt4 book ai didi

android - 从 SQLite 数据库填充 ListView

转载 作者:行者123 更新时间:2023-11-29 14:52:26 25 4
gpt4 key购买 nike

我正在尝试从 SQLite 数据库填充 ListView 我可以创建数据库并向其添加项目并将它们显示在 TextView 中,但由于某种原因不在 ListView 上

是不是sData是错误的对象类型?

有人可以帮忙吗?

public void DBTest() {

SQLiteDatabase myDB = null;
String TableName = "myTable";

/* Create a Database. */
try {
myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);

/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (_id integer primary key autoincrement, name text, script text, su short);");

/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (name, script, su)"
+ " VALUES ('hello', 'reboot', 1);");

/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName, null);

int Column1 = c.getColumnIndex("name");
int Column2 = c.getColumnIndex("script");
int Column3 = c.getColumnIndex("su");

// Check if our result was valid.
c.moveToFirst();
String sData="";
if (c != null) {
// Loop through all Results
do {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
sData = sData + Name + " " + Script + " " + su + "\n";
} while (c.moveToNext());
}

ListView lv = (ListView) findViewById(R.id.mainListView);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, sData));

} catch (Exception e) {
Log.e("Error", "Error", e);
} finally {
if (myDB != null)
myDB.close();
}
}

最佳答案

您最终会得到一个只有一个项目的 ListView,即 sData 的值。您需要创建一个列表,例如:

c.moveToFirst();
ArrayList<String> sData = new ArrayList<String>();
if (c != null) {
do {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
sData.add(Name + " " + Script + " " + su);
} while (c.moveToNext());
}

ListView lv = (ListView) findViewById(R.id.mainListView);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, sData));

我还建议您将光标循环更改为与此类似:

// cursor left as it came from the database because it starts at the row before the first row
ArrayList<String> sData = new ArrayList<String>();
while (c.moveToNext()) {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
sData.add(Name + " " + Script + " " + su);
}

因为目前您没有检查moveToFirst 的返回值,它可能会返回 false(意味着没有行),但是您的 do-while 循环意味着游标将在至少一次,无论它是否有 0 行,如果有 0 行,你的应用程序将崩溃。

关于android - 从 SQLite 数据库填充 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14185630/

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