Книга: 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 you’re 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:

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 constantsCursor = managedQuery(Provider.Constants.CONTENT_URI,
  PROJECTION, nullnullnull);
 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});
 setListAdapter(adapter);
 registerForContextMenu(getListView());
}

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.404. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз