Implementing a Content Provider

A ContentProvider is a high-level object like an Activity that needs to be declared to the system. So, the first step when making one is to add it to your AndroidManifest.xml file before the <activity> tag (as a child of <application>):

Download Eventsv3/AndroidManifest.xml

<provider android:name="'.EventsProvider"

android:authorities= "org.example.events" />

android:name is the class name (appended to the manifest's package name), and android:authorities is the string used in the content URI.

Next we create the EventsProvider class, which must extend ContentProvider. Here's the basic outline:

Download Eventsv3/src/org/example/events/EventsProvider.java

package org.example.events;

import static android.provider.BaseColumns._ID; import static org.example.events.Constants.AUTHORITY; import static org.example.events.Constants.CONTENT_URI; import static org.example.events.Constants.TABLE_NAME; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.text.TextUtils;

public class EventsProvider extends ContentProvider { private static final int EVENTS = 1; private static final int EVENTS_ID = 2;

/** The MIME type of a directory of events */ private static final String CONTENT_TYPE

= "vnd.android.cursor.dir/vnd.example.event";

/** The MIME type of a single event */ private static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.example.event";

private EventsData events; private UriMatcher uriMatcher; // ...

By convention we use vnd.example instead of org.example in the MIME type.4 EventsProvider handles two types of data:

• EVENTS (MIME type CONTENT_TYPE): A directory or list of events

• EVENTS_ID (MIME type CONTENT_ITEM_TYPE): A single event

In terms of the URI, the difference is that the first type does not specify an ID, but the second type does. We use Android's UriMatcher class to parse the URI and tell us which one the client specified. And we reuse the EventsData class from earlier in the chapter to manage the real database inside the provider.

In the interest of space, I'm not going to show the rest of the class here, but you can download the whole thing from the book website. All three versions of the Events example can be found in the source code .zip file.

The final version of the Events sample looks exactly like the previous version on the outside (see Figure 9.3, on page 192). On the inside, however, you now have the framework for an event store that can be used by other applications in the system, even ones written by other developers.

0 0

Post a comment