嗨,我有一個SQLite數據庫,我用一個簡單的遊標讀取數據庫,然後將其顯示給TextView。但是,我想在ListView中顯示數據。在ListView中顯示SQLite
所以我有字符串,但我不知道如何在ListView中顯示它。有沒有簡單的方法,還是我必須創建一個適配器?
我還想知道如何設置列表視圖的部分到標題和其他人的子標題。如果可能的話,我希望每行都是不同的列表項。
嗨,我有一個SQLite數據庫,我用一個簡單的遊標讀取數據庫,然後將其顯示給TextView。但是,我想在ListView中顯示數據。在ListView中顯示SQLite
所以我有字符串,但我不知道如何在ListView中顯示它。有沒有簡單的方法,還是我必須創建一個適配器?
我還想知道如何設置列表視圖的部分到標題和其他人的子標題。如果可能的話,我希望每行都是不同的列表項。
下面是一個簡單的例子:
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). */));
下面是一個簡單example.Lets說你有兩個數組列表命名爲您的主要活動「項目」和「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());
}
現在使用主活動中的Items數組列表填充您的列表視圖。
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, Items);
listview.setAdapter(adapter);
聽起來像你想[SimpleCursorAdapter](http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html)。如果你發佈你的表格模式和你想顯示的列,我會更好地理解你的問題。 – Sam 2012-07-16 20:41:49
你試過了嗎? – 2012-07-16 20:43:00
我只想顯示我的數據庫中的兩列。 – user1261404 2012-07-16 20:49:36