|
Cyril Sermon (@admin) |
Create a new Content Provider by extending the abstract ContentProvider class. Override the onCreate method to open or initialize the underlying data source you’re exposing with this new provider. The skel-eton code for a new Content Provider is shown below:
import android.content.*;
import android.database.Cursor;
import android.net.Uri;
import android.database.SQLException;
public class MyProvider extends ContentProvider {
@Override
public boolean onCreate() {
//TODO: Construct the underlying database. return true;
}
}
You should also expose a public static CONTENT_URI variable that returns the full URI to this provider. Content URIs must be unique between providers, so it’s good practice to base the URI path on your package name. The general form for defining a Content Provider’s URI is
content://com.<CompanyName>.provider.<ApplicationName>/<DataPath>
For example:
content://com.paad.provider.myapp/items
Content URIs can represent either of two forms. The previous URI represents a request for all values of that type (e.g., all items).
Appending a trailing /<rownumber>, as shown below, represents a request for a single record (e.g., “the fifth item”).
content://com.paad.provider.myapp/items/5
It’s good form to support access to your provider using both these forms.
The simplest way to do this is using a UriMatcher. Configure the UriMatcher to parse URIs to deter-mine their form when the provider is being accessed through a Content Resolver. The following snippet shows the skeleton code for this pattern:
public class MyProvider extends ContentProvider {
private static final String myURI =
“content://com.paad.provider.myapp/items”;
public static final Uri CONTENT_URI = Uri.parse(myURI);
@Override
public boolean onCreate() {
//TODO: Construct the underlying database. return true;
}
Create the constants used to differentiate between the different URI requests.
private static final int ALLROWS = 1;
private static final int SINGLE_ROW = 2;
private static final UriMatcher uriMatcher;
Populate the UriMatcher object, where a URI ending in ‘items’ will
correspond to a request for all items, and ‘items/[rowID]’
represents a single row.
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(“com.paad.provider.myApp”, “items”, ALLROWS); uriMatcher.addURI(“com.paad.provider.myApp”, “items/#”,
SINGLE_ROW);
}
}
You can use the same technique to expose alternative URIs for different subsets of data, or different tables within your database from within the same Content Provider.
It’s also good practice to expose the names and indexes of the columns available in your provider to simplify extracting information from Cursor results.