gpt4 book ai didi

java - Android - 在 ListView 中显示所有 SQLite 数据库条目

转载 作者:行者123 更新时间:2023-12-02 00:14:13 25 4
gpt4 key购买 nike

我想要做的是在 ListView 中显示数据库的内容。布局包含一个我已经使用和实现的 ListView,但我似乎无法让它们一起工作(甚至光标),有人可以帮助我并解释为什么我的光标实现不起作用吗?

我有一个方法将数据库条目作为游标返回:

public Cursor getAllRecords() {
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TEXT}, null, null, null, null, null);
}

我有一个要插入和显示数据库条目的类:

Button add;
EditText tM;
ListView generalList;
DBAdapter dba = new DBAdapter(this);

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_general);

add = (Button) findViewById(R.id.button1);
tM = (EditText) findViewById(R.id.editText1);
generalList = (ListView) findViewById(R.id.generalList);

Cursor c = dba.getAllRecords();
c.moveToFirst();

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.id.generalList, c, new String[] {dba.KEY_TEXT}, new int[] {R.id.generalList}, 0);
// This doesn't seem to work for me, I don't know how to fix it
// or how to then get it working with the ListView

generalList.setAdapter(adapter);

add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
insertIntoDatabase();
}
});
}

public void insertIntoDatabase() {
dba.open();
dba.insertRecord(textMessage.getText().toString());
Toast.makeText(this, "Added:\n" + tM.getText().toString(), Toast.LENGTH_LONG).show();
dba.close();
}

最佳答案

当将 ListView 与 CursorAdapter 一起使用时,从列返回的 Cursor 必须包含一个名称为 _id 的列,唯一标识每一行。我猜测您正在获取的一列(dba.KEY_TEXT)未命名为“_id”。您可以向名为 _id 的表添加一列,或者在执行 SELECT 时让数据库返回名称为 _id

SELECT col_name as _id FROM my_table;

或者

SELECT col_name _id FROM my_table;

关于java - Android - 在 ListView 中显示所有 SQLite 数据库条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12169629/

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