我的数据库已全部设置并运行。但现在我遇到的问题是将它加载到列表视图中。我已经尝试了网站上的其他问题,但没有回答我的问题。从初学者(ish)的角度来看。我该怎么做才能将数据库加载到列表视图中?
这是我在课堂上的:(显示类在底部)
public class Inventory extends Activity {
DBAdapter db = new DBAdapter(this);
private Cursor cursor = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inventory_screen);
try {
String destPath = "/data/data/" + getPackageName()
+ "/databases/InventoryDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB(getBaseContext().getAssets().open("InventoryDB"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
DBAdapter db = new DBAdapter(this);
try {
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst()) {
do {
DisplayRecord(c);
} while (c.moveToNext());
}
db.close();
} catch (Exception e) {
Log.e("ERROR", "ERROR IN CODE:" + e.toString());
e.printStackTrace();
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
// ---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
// List View
public void DisplayRecord(Cursor c) {
ListView InventoryItems = (ListView) findViewById(R.id.listViewInventory);
String[] Items = new String[] {c.getString(1)};
ArrayAdapter<String> ItemsAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, Items);
InventoryItems.setAdapter(ItemsAdapter);
//Toast msg = Toast.makeText(Inventory.this, "id: " + c.getString(0)
// + "\n" + "Item: " + c.getString(1) + "\n", Toast.LENGTH_SHORT);
//msg.show();
}
我只是设置了一个列表视图来提取数据库中的第一个项目(这就是我所有的知识延伸到)
我如何让它显示所有数据?我听说过 simpleCursorAdapter,但我不知道这是否相关?