Extending Content Provider

Implementing our BookProvider sample content provider involves extending the ContentProvider class and overriding onCreate() to create the database and then implement the query, insert, update, delete, and getType methods. This section covers the setup and creation of the database, while the following sections deal with each of the individual methods: query, insert, update, delete, and getType.

A query method requires the set of columns it needs to return. This is similar to a select clause that requires column names along with their as counterparts (sometimes called synonyms). Android uses a map object that it calls a projection map to represent these column names and their synonyms. We will need to set up this map so we can use it later in the query-method implementation. In the code for the provider implementation (see Listing 3-25), you will see this done up front.

Most of the methods we'll be implementing take a URI as an input. The provider implementation needs a mechanism to distinguish one URI from the other; Android uses a class called UriMatcher for this work. So we need to set up this object with all our URI variations. You will see this code in Listing 3-25 after the segment that creates a projection map. We'll further explain the UriMatcher class in the section "Using UriMatcher to Figure Out the URIs," but for now, know that the code shown here allows the content provider to identify one URI vs. the other.

And finally, the code in Listing 3-25 overrides the onCreate() method to facilitate the database creation. We have demarcated the code with highlighted comments to reflect the three areas we have talked about here:

• Setting up a column projection

• Setting up the UriMatcher

• Creating the database

Listing 3-25. Implementing the BookProvider Content Provider public class BookProvider extends ContentProvider {

//Create a Projection Map for Columns

//Projection maps are similar to "as" construct in an sql

//statement whereby you can rename the

//columns.

private static HashMap<String, String> sBooksProjectionMap;

static {

sBooksProjectionMap = new HashMap<String, String>(); sBooksProjectionMap.put(BookTableMetaData. _ID, BookTableMetaData._ID);

//name, isbn, author sBooksProjectionMap.put(BookTableMetaData.BOOK_NAME

, BookTableMetaData.BOOK_NAME); sBooksProjectionMap.put(BookTableMetaData.BOOK_ISBN

, BookTableMetaData.BOOK_ISBN); sBooksProjectionMap.put(BookTableMetaData.BOOK_AUTHOR

, BookTableMetaData.BOOK_AUTHOR);

//created date, modified date sBooksProjectionMap.put(BookTableMetaData.CREATED_DATE

, BookTableMetaData.CREATED_DATE); sBooksProjectionMap.put(BookTableMetaData.MODIFIED_DATE

, BookTableMetaData.MODIFIED_DATE);

0 0

Post a comment