我在学习 SQLite 世界的细节方面遇到了一些困难。我有一些代码允许我将数据输入数据库。但我想做的是将这些数据返回到 ListView 中。目前我能想到的就是在添加新条目后将每一行打印在 toast 中。有人可以告诉我如何更改我的代码以在 ListView 中打印它吗?或者甚至查看我的代码,看看我是否以正确的方式处理它。谢谢
这是我正在使用的代码,它调用显示记录函数
//---get all Records---
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
do {
DisplayRecord(c);
} while (c.moveToNext());
}
db.close();
这是显示记录功能
public void DisplayRecord(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"Item: " + c.getString(1) + "\n" +
"Litres: " + c.getString(2),
Toast.LENGTH_SHORT).show();
}
我知道我需要更改第二个函数,但我不知道如何将其打印到 ListView 中
最佳答案
这是从数据库获取数据并插入 Arraylist 和 arrayAdapter 并在 listview 中显示的代码。
我刚刚对您现有的代码进行了一些编辑。
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
db.open();
ArrayList<String> data_list=new ArrayList<String>();
ListView lv=(ListView)findViewById(R.id.listView1);
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
do {
data_list.add(c.getString(0));
DisplayRecord(c);
} while (c.moveToNext());
}
ArrayAdapter<String> aa=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, data_list);
lv.setAdapter(aa);
lv - 是ListView的对象。
关于java - 将 SQLite 条目打印到 ListView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26700897/