【问题标题】:Android populate ListView from Sqlite DBAndroid 从 Sqlite DB 填充 ListView
【发布时间】:2016-05-29 23:52:09
【问题描述】:

我会尝试解释我的问题。我创建了一个基于 Zxing 库的小项目,用于读取和存储条形码。现在我要创建我的第一个 ListView,其中包含来自工作 SQLite db 的元素。 这是我的源代码的摘录

数据库适配器

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。有人可以帮我吗?

【问题讨论】:

    标签: android database sqlite listview


    【解决方案1】:

    由于您的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 有一堆你可以使用的布局,这又取决于。如果您想查看这些布局,这里是 link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多