@kimo
2016-01-08T08:07:26.000000Z
字数 4939
阅读 1763
android
public final class FeedReaderContract {// To prevent someone from accidentally instantiating the contract class,// give it an empty constructor.public FeedReaderContract() {}/* Inner class that defines the table contents */public static abstract class FeedEntry implements BaseColumns {public static final String TABLE_NAME = "entry";public static final String COLUMN_NAME_ENTRY_ID = "entryid";public static final String COLUMN_NAME_TITLE = "title";public static final String COLUMN_NAME_SUBTITLE = "subtitle";...}}
SQLiteOpenHelper class.getWritableDatabase() or getReadableDatabase().(Because they can be long-running, be sure that you call getWritableDatabase() or getReadableDatabase() in a background thread, such as with AsyncTask or IntentService.)For example, here's an implementation of SQLiteOpenHelper
public class FeedReaderDbHelper extends SQLiteOpenHelper {private static final String TEXT_TYPE = " TEXT";private static final String COMMA_SEP = ",";private static final String SQL_CREATE_ENTRIES ="CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +FeedEntry._ID + " INTEGER PRIMARY KEY," +FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +... // Any other options for the CREATE command" )";private static final String SQL_DELETE_ENTRIES ="DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;// If you change the database schema, you must increment the database version.public static final int DATABASE_VERSION = 1;public static final String DATABASE_NAME = "FeedReader.db";public FeedReaderDbHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}public void onCreate(SQLiteDatabase db) {db.execSQL(SQL_CREATE_ENTRIES);}public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// This database is only a cache for online data, so its upgrade policy is// to simply to discard the data and start overdb.execSQL(SQL_DELETE_ENTRIES);onCreate(db);}public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {onUpgrade(db, oldVersion, newVersion);}}
To access your database, instantiate your subclass of SQLiteOpenHelper:
FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());
Insert data into the database by passing a ContentValues object to the insert() method:
// Gets the data repository in write modeSQLiteDatabase db = mDbHelper.getWritableDatabase();// Create a new map of values, where column names are the keysContentValues values = new ContentValues();values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);values.put(FeedEntry.COLUMN_NAME_TITLE, title);values.put(FeedEntry.COLUMN_NAME_CONTENT, content);// Insert the new row, returning the primary key value of the new rowlong newRowId;newRowId = db.insert(FeedEntry.TABLE_NAME,FeedEntry.COLUMN_NAME_NULLABLE,values);
The first argument for insert() is simply the table name. The second argument provides the name of a column in which the framework can insert NULL in the event that the ContentValues is empty (if you instead set this to "null", then the framework will not insert a row when there are no values).
SQLiteDatabase db = mDbHelper.getReadableDatabase();// Define a projection that specifies which columns from the database// you will actually use after this query.String[] projection = {FeedEntry._ID,FeedEntry.COLUMN_NAME_TITLE,FeedEntry.COLUMN_NAME_UPDATED,...};// How you want the results sorted in the resulting CursorString sortOrder =FeedEntry.COLUMN_NAME_UPDATED + " DESC";Cursor c = db.query(FeedEntry.TABLE_NAME, // The table to queryprojection, // The columns to returnselection, // The columns for the WHERE clauseselectionArgs, // The values for the WHERE clausenull, // don't group the rowsnull, // don't filter by row groupssortOrder // The sort order);
To look at a row in the cursor, use one of the Cursor move methods, which you must always call before you begin reading values. Generally, you should start by calling moveToFirst(), which places the "read position" on the first entry in the results. For each row, you can read a column's value by calling one of the Cursor get methods, such as getString() or getLong(). For each of the get methods, you must pass the index position of the column you desire, which you can get by callinggetColumnIndex() or getColumnIndexOrThrow(). For example:
cursor.moveToFirst();
long itemId = cursor.getLong(
cursor.getColumnIndexOrThrow(FeedEntry._ID)
);
// Define 'where' part of query.String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";// Specify arguments in placeholder order.String[] selectionArgs = { String.valueOf(rowId) };// Issue SQL statement.db.delete(table_name, selection, selectionArgs);
SQLiteDatabase db = mDbHelper.getReadableDatabase();// New value for one columnContentValues values = new ContentValues();values.put(FeedEntry.COLUMN_NAME_TITLE, title);// Which row to update, based on the IDString selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";String[] selectionArgs = { String.valueOf(rowId) };int count = db.update(FeedReaderDbHelper.FeedEntry.TABLE_NAME,values,selection,selectionArgs);