0

嗨,我有一个 SQLite 数据库,我正在使用一个简单的光标来读取数据库,然后将其显示给 TextView。但是,我想在 ListView 中显示数据。

所以我有字符串,但我不知道如何在 ListView 中显示它。有没有简单的方法或者我必须创建一个适配器?

我还想知道如何将列表视图的一部分设置为标题,将其他部分设置为副标题。如果可能的话,我希望每一行都是不同的列表项。

4

2 回答 2

1

这是一个简单的示例。假设您的主要活动中有两个名为“Items”和“ItemsId”的数组列表。现在,在您的数据库处理程序类中,使用以下代码获取您的表并将值存储到 Items 和 ItmesId 数组列表中。

    MainActivity.Items.clear();
    MainActivity.ItemsId.clear();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            // Adding values to list
            MainActivity.Items.add(cursor.getString(0));
            MainActivity.ItemsId.add(cursor.getString(0));
           } while (cursor.moveToNext());
    }

现在使用 Main 活动中的 Items 数组列表填充您的列表视图。

final StableArrayAdapter adapter = new StableArrayAdapter(this,
    android.R.layout.simple_list_item_1, Items);
listview.setAdapter(adapter);
于 2013-05-17T04:42:41.227 回答
0

使用SimpleCursorAdapter

这是一个简单的例子:

    yourListView.setAdapter(new SimpleCursorAdapter(
    /* The context where the ListView associated with this SimpleListItemFactory is running */, 
    /* resource identifier of a layout file that defines the views for this list item. The layout file should include at least those named views defined in "to" */, 
    /* The database cursor. Can be null if the cursor is not available yet. */,
    /* A list of column names representing the data to bind to the UI. Can be null if the cursor is not available yet. */, 
    /* The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter. Can be null if the cursor is not available yet. */, 
    /* Flags used to determine the behavior of the adapter, as per CursorAdapter(Context, Cursor, int). */));
于 2012-07-16T21:00:29.603 回答