Readquery data

To read data, use the managedQuery method. This is an Activity method that calls query internally. It manages the query for the developer, closing the Cursor and re-querying it when necessary. The parameters passed to managedQuery are:

The URI to query. This will map to a specific content provider, and in NotePad's case, to the NotePad content provider.


A String array with one element for each column you want returned in the query. Columns are numbered and correspond to the order of the columns in the underlying database. selection

Indicates which rows to retrieve through an SQL WHERE clause; it is passed as a single String variable. Can be NULL if you want all rows.


A String array containing one argument for each parameter or placeholder (a question mark in the SQL SELECT statement). Pass NULL if there are no arguments. sortOrder

A String variable containing a full ORDER BY argument, if sorting is desired. Can be NULL.

The NotePad application queries the NotePadProvider to fill in the list of notes to display to the user:

public class NotesList extends ListActivity {

private static final String[] PROJECTION = new String[] {O Notes._ID, // 0 Notes.TITLE, // 1

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);


// If no data was given in the Intent (because we were started // as a MAIN activity), then use our default content provider. Intent intent = getIntent(); if (intent.getData() == null) {


// Inform the list we provide context menus for items getListView().setOnCreateContextMenuListener(this);

// Perform a managed query. The Activity will handle closing

// and requerying the cursor when needed.

Cursor cursor = managedQuery(getIntent().getData(),0


// Used to map notes entries from the database to views SimpleCursorAdapter adapter = new SimpleCursorAdapter( this,

R.layout.noteslist_item, cursor, new String[] { Notes.TITLE }, new int[] { }); setListAdapter(adapter);©

Here are some of the highlights of the code:

O Creates the projection, the first parameter to managedQuery. In this case, the array contains the note ID and title.

© Sets the Activity's default key handling mode to DEFAULT_KEYS_SHORTCUTS. This lets the user execute shortcut commands from the options menu without having to press the menu key first.

© Gets the client's request, passed in the Intent. This should contain the content provider URI, but if it doesn't, the next line sets it to the NotePad URI.

O The managedQuery call, which returns a cursor.

© To use the data in the Cursor as the input for a ListActivity, an Adapter is required. In this case, a SimpleCursorAdapter has all the functionality that is necessary.

© After you have created the Adapter, issue the ListActivity's setListAdapter method to display the data from the Cursor on the screen.

0 0

Post a comment