SimpleCursorAdapters are used to take a cursor (data from a SQL query) and map it to a View (a widget in your UI like a ListView).
I found several parameters very confuzzling the first, second and third time I used SimpleCursorAdapters. Lets break-down the odd parameter list:
SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to)
Context context – If you aren’t sure what this is, go google it.
int layout – Notice this is an integer. This field tells the adapter the id of the layout you will be using to display your results. This works in conjunction with the to parameter.
Cursor c – Your cursor object
String[] from – The name of the columns from your database that you want to display junk from.
int[] to – The id of the view(s) that you want your junk displayed on
So this seems fairly simple, and my definition of these terms really doesn’t deviate far from the built-in help viewer. But in every example that uses SimpleCursorAdapter you will find that they set the layout parameter to android.R.layout.simple_list_item_1. The problem/confusion comes in here, how do we know what Views are contained in android.R.layout.simple_list_item_1 so that we can properly set the to parameter?!?
Well to save us all trouble, someone out there had the android source and posted the contents of these items:
simple_list_item_1:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="android:attr/listItemFirstLineStyle"
android:paddingTop="2dip"
android:paddingBottom="3dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
simple_list_item_2:
<TwoLineListItem xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="2dip"
android:paddingBottom="2dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView android:id="@android:id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="android:attr/listItemFirstLineStyle"
/>
<TextView android:id="@android:id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@android:id/text1"
style="android:attr/listItemSecondLineStyle"
/>
</TwoLineListItem>
So, to make the rubber meet the road. If you are using simple_list_item_1 then you need your to parameter to be android.R.id.text1.
Your code might look like this, note I’m using a database helper class to perform my SQL query and get my results.
DbAdapter.KEY_TITLE = "name":
Cursor c = mDbHelper.getAllEntries();
startManagingCursor(c);
ListAdapter adapter =
new SimpleCursorAdapter(mContext, android.R.layout.simple_list_item_1, c, new String[] {DbAdapter.KEY_TITLE}, new int[] {android.R.id.text1});
listView.setAdapter(adapter);
Like this:
Like Loading...