[英]Android populate ListView from Sqlite DB
我會盡力解釋我的問題。 我已經基於Zxing庫創建了一個小項目,用於讀取和存儲條形碼。 現在,我必須創建第一個ListView,其中包含工作SQLite數據庫中的元素。 這是我的源代碼的一部分
DBAdapter
public boolean insertProduct(String barcode, int quantity)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_BARCODE, barcode);
initialValues.put(KEY_QUANTITY, quantity);
try {
db.insert(DATABASE_TABLE, null, initialValues);
return true;
}
catch(Exception ex){
return false;
}
}
public boolean deleteProduct(String barcode)
{
return db.delete(DATABASE_TABLE, KEY_BARCODE + "=" + barcode, null) > 0;
}
public Cursor getAllProducts()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_BARCODE, KEY_QUANTITY}, null, null, null, null, null);
}
現在,我不知道如何在Activity類中填充ListView。 有人可以幫我嗎?
由於您的getAllProducts()
將返回游標,因此可以使用游標適配器。 這是活動類的一些示例代碼:
Cursor cursor = db.query(DATABASE_TABLE,
new String[] {KEY_ROWID, KEY_BARCODE, KEY_QUANTITY}, null, null, null, null, null);
CursorAdapter listAdapter = new SimpleCursorAdapter(this,
_id_of_your_item_layout, // You'll have to make your own item layout
cursor,
new String[] {KEY_ROWID, KEY_BARCODE, KEY_QUANTITY},
new int[]{id_of_textview_1, id_of_textview_2, id_of_textview_3}, 0);
這是細分:
CursorAdapter listAdapter = new SimpleCursorAdapter(Context context,
int layoutID,
Cursor cursor,
String[] {FromColumns},
int[] {toViews}, int flags);
值得注意的是,您不必使用自己的項目布局。 這完全取決於每個列表項中需要多少個字段以及它們如何顯示。 Android有很多可供使用的布局,這又取決於它。 如果您想簽出這些布局,請點擊這里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.