SQLite In Android Part 1: The Contract Classes

When using an SQLiteDatabase in your Android applications, especially with a ContentProvider, it is very helpful to first define a few contract classes. These classes are used to define the table structure for each of the tables in your database, as well as define any necessary Uris to write to or read from those tables. In the first of four posts about using SQLite in Android, we’ll discuss how to make the contract classes, and then move on to creating the database using these classes.

Before we begin, you’ll need to know some necessary background information regarding the tutorial:

  • We will be creating a movie database with two tables.
    • Genres, which records a genre name.
    • Movies, which records the movie genre (a foreign key to the previous table), name, and release date.

The Content Authority

Let’s start with the content authority and other class level variables for our contract class:

The CONTENT_AUTHORITY string is a name used throughout the entire ContentProvider, similar to a domain name for a website. The BASE_CONTENT_URI, as the name implies, is our base for all Uris that will access our database. PATH_MOVIE and PATH_GENRE are strings that will be appended to our Uris to define which tables will be accessed by the ContentProvider.

The Table Entries

As subclasses of MovieContract, we will create a class for each of our tables in the database. Each class must have the following information:

  • A CONTENT_URI that represents the base location for the database table.
  • A CONTENT_TYPE and CONTENT_ITEM_TYPE string which are basic type prefixes to define whether or not a Uri will be returning a list or a specific item from the table. These will take the form of “vnd.android.cursor.dir/” and “vnd.android.cursor.item/”, respectively.
  • A TABLE_NAME string as well as a string for all of the column names.
  • A buildTableUri() function to build a Uri for a specific row in the table.

Our GenreEntry class will look like this:

With the only difference of naming conventions and column strings, our MovieEntry class will be identical. If you would like to review it, you can find the source code for this entire file in Github.

That concludes the first part of this segment on using SQLite in Android. Head on over to part 2 to see how the contract classes our used in our SQLiteOpenHelper.

Share this post...
Share on Reddit0Share on Google+1Tweet about this on TwitterShare on LinkedIn0Share on Facebook0

Leave a Reply