我想要做的是在 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();
}