: Beginning Android

Adapting to the Circumstances

Adapting to the Circumstances

Now that we have a Cursor via managedQuery(), we have access to the query results and can do whatever we want with them. You might, for example, manually extract data from the Cursor to populate widgets or other objects.

However, if the goal of the query was to return a list from which the user should choose an item, you probably should consider using SimpleCursorAdapter. This class bridges between the Cursor and a selection widget, such as a ListView or Spinner. Pour the Cursor into a SimpleCursorAdapter, hand the adapter off to the widget, and youre set your widget will show the available options.

For example, here is the onCreate() method from ConstantsBrowser, which gives the user a list of physical constants:

public voidonCreate(Bundle savedInstanceState) {
constantsCursor =managedQuery(Provider.Constants.CONTENT_URI,
ListAdapter adapter =new SimpleCursorAdapter(this,
R.layout.row, constantsCursor,
new String[] {Provider.Constants.TITLE, Provider.Constants.VALUE},
new int[] {R.id.title, R.id.value});

After executing the managedQuery() and getting the Cursor, ConstantsBrowser creates a SimpleCursorAdapter with the following parameters:

The activity (or other Context) creating the adapter; in this case, the ConstantsBrowser itself

The identifier for a layout to be used for rendering the list entries (R.layout.row)

The cursor (constantsCursor)

The properties to pull out of the cursor and use for configuring the list entry View instances (TITLE and VALUE)

The corresponding identifiers of TextView widgets in the list entry layout that those properties should go into (R.id.title and R.id.value)

After that, we put the adapter into the ListView, and we get the results shown in Figure 27-1.

Figure 27-1.ConstantsBrowser, showing a list of physical constants

If you need more control over the views than you can reasonably achieve with the stock view construction logic, subclass SimpleCursorAdapter and override getView() to create your own widgets to go into the list, as demonstrated in Chapter 9.

: 1.062. /Cache: 3 / 0