Reputation: 325
Hi, I have an SQLite database and I'm using a simple cursor to read the database and then show it to a TextView. However, I would like to show the data in a ListView.
So I have the string but I don't know how to show it in ListView. Is there a simple method or will I have to create an adapter of sorts?
I was also wondering how you can set parts of the list view to the header and others to the subheading. I want it so that each row is a different list item if that's possible.
Upvotes: 0
Views: 159
Reputation: 5440
Here is a simple example.Lets say you have two array lists named "Items" and "ItemsId" in your main activity. Now, in your database handler class fetch your table and store the values to the Items and ItmesId array lists using below code.
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());
}
Now populate your list view with Items array list in Main activity.
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, Items);
listview.setAdapter(adapter);
Upvotes: 1
Reputation: 34614
Use the SimpleCursorAdapter.
Here is a trivial example:
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). */));
Upvotes: 0