A contract class is a public final class that contains constant definitions for the URIs, column names, MIME types, and other meta-data about the ContentProvider. It can also contain static helper methods to manipulate the URIs. In simple terms, Contract class is used by the developers to define a schema and have a convention where to find the database constants.
Why we use contract classes?
There are two more reasons apart from defining schema and grouping constants.
1. When generating SQL commands, remove possibilities of introducing spelling errors. For example, while creating SQL command as given below could introduce errors and thus using contract class and having constants defined eliminate these errors.
String statement = "CREATE TABLE entry (
_id INTEGER PRIMARY KEY",
entryid TEXT,
title TEXT);"
Using constants
String statement = "CREATE TABLE + FeedEntry.TABLE_NAME + "(" +
FeedEntry._ID + "INTEGER PRIMARY KEY," +
FeedEntry.COLUMN_NAME_ENTRY_ID + "TEXT, " +
FeedEntry.COLUMN_NAME_TITLE + "TEXT);"
2. Ease of updating the database schema. Consider you are referencing table name more than one place in your project and wants to change it. The only place you would have to change is the contract class.
Now, let’s discuss the structure of the Contract class. These are the three components for a general Contract class. (Note: In the example below, “Your” can be replaced by the name relevant to the project)
1. Outer class name YourContract
2. Inner class name YourEntry for each table in the database. Each of these inner classes should implement a class called BaseColumns.
3. String constants for table name and for each of the readings (e.g. TABLE_NAME, COLUMN_CITY_NAME, etc).
All that being said where should we actually create this class?
Since in real world we work with a lot of classes that have to do with data, we create a new package for the contract class and this is done to separate classes with data specific functionality from the activity related classes. This package is created under the existing package.
You can visit this link to see the CalenderContract used by Google in the calendar app. https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/provider/CalendarContract.java
If you visited the link, you would have seen the contract class is declared final and that is because it’s just a class for providing constants and we won’t need to extend or implement anything for this outer class.