Android Tutorial

(avery) #1

By : Ketan Bhimani


350 

Implementing Important Content Provider Methods

This section shows example implementations of each of the
methods that are used by the system to call this content provider
when another application wants to use it. The system, in this case,
is the ContentResolver interface that was used indirectly in the
previous section when built-in content providers were used.

Some of these methods can make use of a helper class provided by
the Android SDK, UriMatcher, which is used to match incoming Uri
values to patterns that help speed up development.The use of
UriMatcher is described and then used in the implementation of
these methods.

Implementing the query() Method

Let’s start with a sample query implementation. Any query
implementation needs to return a Cursor object. One convenient
way to get a Cursor object is to return the Cursor from the
underlying SQLite database that many content providers use. In
fact, the interface to ContentProvider.query() is compatible with the
SQL ite Query Builder .query() call. This example uses it to quickly
build the query and return a Cursor object.

public Cursor query(Uri uri, String[] projection,
String selection, String[] selectionArgs,
String sortOrder) {
SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
qBuilder.setTables(TrackPointDatabase.TRACKPOINTS_TABLE);
if ((sURIMatcher.match(uri)) == TRACKPOINT_ID) {
qBuilder.appendWhere(“_id=” + uri.getLastPathSegment());
}
Cursor resultCursor = qBuilder.query(mDB.getReadableDatabase(),
projection, selection, selectionArgs, null, null, sortOrder, null);
resultCursor.setNotificationUri(getContext().getContentResolver(),
uri);
return resultCursor;
}

Free download pdf