您的合同基本上定义了您的数据库以及人们应该如何通过内容提供者与之交互。
契约类定义了帮助应用程序使用内容 URI、列名、意图操作和内容提供者的其他功能的常量。合同类不会自动包含在提供者中;提供者的开发者必须定义它们,然后将它们提供给其他开发者。
话虽如此,您不一定需要 Content Provider 才能使用 Contract 类。我的示例包含 Content Provider 使用的常量(MIME 和 URI 部分)。如果您不使用 Content Provider,则不需要这些部分。
我喜欢将合同类视为数据库模式,或者换句话说,它定义了数据库的设置方式。您可能会注意到合约类中的所有内容都被声明为静态的。那是因为您永远不会实例化 Contract 类,而只会引用其中定义的常量。您可以在我的示例中看到,我的 Contract 类只声明了一堆静态最终变量。这个Contract 类可以是它自己的文件,例如我的文件叫做TransitContract.java。
例如,假设您想更改其中一列的名称。您只需更改合同类中列的值,而不是更改多个文件。您没有在合约类中进行任何类型的计算工作。
另一方面,SQLLiteOpenhelper 类是由 Google 提供的,用于简化数据库操作。这是您实现创建和设置初始数据库的方法的地方。请参阅http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html。实现这些方法后,您所要做的就是实例化您的助手类的实例,然后调用 helperClassInstance.getWriteableDatabase()(或 getReadableDataBase()),然后您的助手类会在必要时自动负责创建新数据库,或返回一个已经存在的,等等。
这个助手通常作为一个内部类实现,但也可以是它自己的独立类。但是,您要实现它。
我强烈建议您查看 Google 提供的记事本示例,因为它有一个很好的示例来说明如何设置合同类别。请注意,他们还使用内容提供程序。如果您有兴趣了解内容提供程序,我建议您在http://developer.android.com/guide/topics/providers/content-provider-basics.html阅读更多内容。它更深入地介绍了 Content Providers 和 Contract 类。
这是使用您的代码的示例。我实际上并没有测试这段代码,所以它可能有错误。如您所见,您可以在任何您认为必要的地方实例化您的数据库助手。在此示例中,我在主要活动的 onCreate 中执行此操作,但实际上这是不好的做法。
数据库合同.java
public final class DatabaseContract {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "database.db";
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
// To prevent someone from accidentally instantiating the contract class,
// give it an empty constructor.
private DatabaseContract() {}
public static abstract class Table1 implements BaseColumns {
public static final String TABLE_NAME = "nameOfTable";
public static final String COLUMN_NAME_COL1 = "column1";
public static final String COLUMN_NAME_COL2 = "column2";
public static final String COLUMN_NAME_COL3 = "column3";
public static final String CREATE_TABLE = "CREATE TABLE " +
TABLE_NAME + " (" +
_ID + " INTEGER PRIMARY KEY," +
COLUMN_NAME_COL1 + TEXT_TYPE + COMMA_SEP +
COLUMN_NAME_COL2 + TEXT_TYPE + COMMA_SEP +
COLUMN_NAME_COL3 + TEXT_TYPE + " )";
public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
}
}
数据库助手.java
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DatabaseContract.DATABASE_NAME, null, DatabaseContract.DATABASE_VERSION);
}
// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DatabaseContract.Table1.CREATE_TABLE);
}
// Method is called during an upgrade of the database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DatabaseContract.Table1.DELETE_TABLE);
onCreate(db);
}
}
MainActivity.java
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create new helper
DatabaseHelper dbHelper = new DatabaseHelper(getContext());
// Get the database. If it does not exist, this is where it will
// also be created.
SQLiteDatabase db = dbHelper.getWriteableDatabase();
// Create insert entries
ContentValues values = new ContentValues();
values.put(DatabaseContract.Table1.COLUMN_NAME_COL1, "value1");
values.put(DatabaseContract.Table1.COLUMN_NAME_COL2, "value2");
values.put(DatabaseContract.Table1.COLUMN_NAME_COL3, "value3");
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
DatabaseContract.Table1.TABLE_NAME,
null,
values);
}
}
我的例子
public final class TransitContract {
public static final String AUTHORITY = "com.example.TransitProvider";
public static final String SCHEME = "content://";
public static final String SLASH = "/";
public static final String DATABASE_NAME = "transit.db";
/* An array list of all the SQL create table statements */
public static final String[] SQL_CREATE_TABLE_ARRAY = {
Agency.CREATE_TABLE,
CalendarDates.CREATE_TABLE,
Calendar.CREATE_TABLE,
Routes.CREATE_TABLE,
Shapes.CREATE_TABLE,
Stops.CREATE_TABLE,
StopTimes.CREATE_TABLE,
Trips.CREATE_TABLE
};
/**
* Array of resource ids for each GTFS data file that will be loaded into
* database
*/
public static final int[] RAW_IDS = {
R.raw.agency,
R.raw.calendar_dates,
R.raw.calendar,
R.raw.routes,
R.raw.shapes,
R.raw.stops,
R.raw.stop_times,
R.raw.trips,
};
/* Do not allow this class to be instantiated */
private TransitContract() {}
public static final class Agency implements BaseColumns {
/* Do not allow this class to be instantiated */
private Agency() {}
public static final String TABLE_NAME = "Agency";
public static final String KEY_AGENCY_ID = "AgencyId";
public static final String KEY_NAME = "Name";
public static final String KEY_URL = "Url";
public static final String KEY_TIMEZONE = "Timezone";
public static final String KEY_LANG = "Language";
public static final String KEY_PHONE = "PhoneNumber";
public static final String KEY_FARE_URL = "FareUrl";
/*
* URI definitions
*/
/**
* The content style URI
*/
public static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + SLASH + TABLE_NAME);
/**
* The content URI base for a single row. An ID must be appended.
*/
public static final Uri CONTENT_ID_URI_BASE = Uri.parse(SCHEME + AUTHORITY + SLASH + TABLE_NAME + SLASH);
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = KEY_AGENCY_ID + " ASC";
/*
* MIME type definitions
*/
/**
* The MIME type of {@link #CONTENT_URI} providing rows
*/
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE +
"/vnd.com.marylandtransitcommuters.agency";
/**
* The MIME type of a {@link #CONTENT_URI} single row
*/
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE +
"/vnd.com.marylandtransitcommuters.agency";
/**
* SQL Statement to create the routes table
*/
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ("
+ _ID + " INTEGER PRIMARY KEY,"
+ KEY_AGENCY_ID + " TEXT,"
+ KEY_NAME + " TEXT,"
+ KEY_URL + " TEXT,"
+ KEY_TIMEZONE + " TEXT,"
+ KEY_LANG + " TEXT,"
+ KEY_PHONE + " TEXT,"
+ KEY_FARE_URL + " TEXT"
+ ");";
/**
* SQL statement to delete the table
*/
public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
/**
* Array of all the columns. Makes for cleaner code
*/
public static final String[] KEY_ARRAY = {
KEY_AGENCY_ID,
KEY_NAME,
KEY_URL,
KEY_TIMEZONE,
KEY_LANG,
KEY_PHONE,
KEY_FARE_URL
};
}