public finalclass FeedReaderContract{ // To prevent someone from accidentally instantiating the contract class,// give it an empty constructor.FeedReaderContract(){}/* Inner class that defines the table contents */staticabstractFeedEntryimplementsBaseColumnsString TABLE_NAME ="entry"; COLUMN_NAME_ENTRY_ID "entryid" COLUMN_NAME_TITLE "title" COLUMN_NAME_SUBTITLE "subtitle"...}}
在合同类中为每张表创建内部类并列举其列。通过实现BaseColumns接口,该内部类会继承一个主键字段"_ID"。它不是必须的,但可以帮你的数据库与Android框架和谐的工作。
2.构造创建表和删除表的语句
private TEXT_TYPE " TEXT" COMMA_SEP "," sql_CREATE_ENTRIES "CREATE TABLE "+FeedEntry.TABLE_NAME " ("_ID " INTEGER PRIMARY KEY,"COLUMN_NAME_ENTRY_ID COLUMN_NAME_TITLE // Any other options for the CREATE command" )" sql_DELETE_ENTRIES "DROP TABLE IF EXISTS "TABLE_NAME;
FeedReaderDbHelperextendssqliteOpenHelper// If you change the database schema,you must increment the database version.int DATABASE_VERSION 1 DATABASE_NAME "FeedReader.db"FeedReaderDbHelper(Context context)super(context,0)"> DATABASE_NAMEnull DATABASE_VERSION);void onCreatesqliteDatabase dbexecsqlsql_CREATE_ENTRIES onUpgrade oldVersion newVersion// This database is only a cache for online data,so its upgrade policy is// to simply to discard the data and start oversql_DELETE_ENTRIESdb onDowngrade}
访问数据库前,先实例化
SQLiteOpenHelper子类:
mDbHelper newgetContext());
4.向数据库中插入数据
// Gets the data repository in write mode db mDbHelpergetWritableDatabase();// Create a new map of values,where column names are the keysContentValues values ContentValues valuesputCOLUMN_NAME_ENTRY_ID idCOLUMN_NAME_TITLE titleCOLUMN_NAME_CONTENT content// Insert the new row,returning the primary key value of the new rowlong newRowId newRowId insertCOLUMN_NAME_NULLABLE);
getReadableDatabase// Define a projection that specifies which columns from the database// you will actually use after this query.String[] projection _IDCOLUMN_NAME_UPDATED};// How you want the results sorted in the resulting Cursor sortOrder COLUMN_NAME_UPDATED " DESC"Cursor c query// The table to query projection// The columns to return selection// The columns for the WHERE clause selectionArgs// The values for the WHERE clause// don't group the rows// don't filter by row groups sortOrder // The sort order);
cursormoveToFirst itemId cursorgetLonggetColumnIndexOrThrow);
// Define 'where' part of query. selection " LIKE ?"// Specify arguments in placeholder order. selectionArgs valueOfrowId// Issue sql statement.deletetable_name);
7.更新数据库中的数据。
// New value for one column// Which row to update,based on the ID count update.);