您的合同基本上定义了您的数据库以及人们应如何通过内容提供商与之交互。
协定类定义可帮助应用程序使用内容 URI、列名、目的操作和内容提供程序的其他功能的常量。合约类不会自动包含在提供程序中;提供程序的开发人员必须定义它们,然后将其提供给其他开发人员。
话虽如此,您不一定需要内容提供程序才能使用 Contract 类。我的示例包含内容提供程序使用的常量(MIME 和 URI 部分)。如果您没有使用内容提供程序,则不需要这些部分。
我喜欢将 contract 类视为数据库模式,或者换句话说,它定义了数据库的设置方式。您可能会注意到,协定类中的所有内容都声明为静态。这是因为您永远不会实例化 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 阅读更多内容。它更深入地介绍了内容提供程序和合同类。
下面是使用代码的示例。我实际上没有测试此代码,因此可能存在错误。如您所见,您可以在任何您认为必要的位置实例化数据库帮助程序。在这个例子中,我在主要活动的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);
}
}
主要活动.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
};
}