package com.memo;
import java.util.HashMap;
import com.memo.MemoContract.Memo;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
/**
* Provides the access to the data of Memo
*/
public class MemoProvider extends ContentProvider {
/**
* a new DbHelper
*/
private DbHelper dbHelper;
/**
* Create and initialize a UriMatcher instance
*/
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);;
// The incoming URI matches the Memo URI pattern
private static final int MEMOS = 1;
// The incoming URI matches the Memo ID URI pattern
private static final int MEMO_ID = 2;
static{
// Add a pattern that routes URIs terminated with "Memos" to a Memos operation
sUriMatcher.addURI(MemoContract.AUTHORITY, "Memo", MEMOS);
// Add a pattern that routes URIs terminated with "Memos" plus an integer
// to a memo ID operation
sUriMatcher.addURI(MemoContract.AUTHORITY, "Memo/#", MEMO_ID);
}
/**
* A projection map used to select columns from the database
*/
private static HashMap<String, String> ProjectionMap;
/* constants for whole database */
private static final String DATABASE_NAME= "db";
private static final int DATABASE_VERSION= 2;
/* table creation SQL statements */
public static final String CREATE_TABLE_MEMO= "create table "+Memo.TABLE_NAME+" ("
+Memo._ID+" integer primary key autoincrement, "
+Memo.COLUMN_NAME_CONTENT+" text)";
/**
* The helper class which manage the database creation and database version upgrade
*/
private class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Create the data table by executing the SQL statement
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_MEMO);
}
/**
*
* Demonstrates that the provider must consider what happens when the
* underlying database is changed. In this sample, the database is upgraded
* by destroying the existing data.
* A real application should upgrade the database in place.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Logs that the database is being upgraded
Log.w(DATABASE_NAME, "Upgrading database from version " + oldVersion + " to " + newVersion
+ ", which will destroy all old data");
// Kills the table and existing data
db.execSQL("DROP TABLE IF EXISTS Memo");
// Recreates the database with a new version
onCreate(db);
}
}
/**
*
* Initializes the provider by creating a new DbHelper. onCreate() is called
* automatically when Android creates the provider in response to a resolver request from a
* client.
*/
@Override
public boolean onCreate() {
// Creates a new helper object. Note that the database itself isn't opened until
// something tries to access it, and it's only created if it doesn't already exist.
dbHelper=new DbHelper(getContext());
// Assumes that any failures will be reported by a thrown exception.
return true;
}
/**
* This method is called when a client calls
* {@link android.content.ContentResolver#query(Uri, String[], String, String[], String)}.
* Queries the database and returns a cursor containing the results.
*
* @return A cursor containing the results of the query. The cursor exists but is empty if
* the query returns no results or an exception occurs.
* @throws IllegalArgumentException if the incoming URI pattern is invalid.
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// Constructs a new query builder and sets its table name
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
/**
* Choose the projection and adjust the "where" clause based on URI pattern-matching.
*/
switch (sUriMatcher.match(uri)) {
// If the incoming URI is for menos, chooses the Memos projection
case MEMOS:
qb.setTables(Memo.TABLE_NAME);
qb.setProjectionMap(ProjectionMap);
break;
/* If the incoming URI is for a single memo identified by its ID, chooses the
* memo ID projection, and appends "_ID = <MemoID>" to the where clause, so that
* it selects that single memo
*/
case MEMO_ID:
qb.setTables(Memo.TABLE_NAME);
qb.setProjectionMap(ProjectionMap);
qb.appendWhere(
Memo._ID + // the name of the ID column
"=" +
// the position of the memo ID itself in the incoming URI
uri.getPathSegments().get(1));
break;
default:
// If the URI doesn't match any of the known patterns, throw an exception.
throw new IllegalArgumentException("Unknown URI " + uri);
}
String orderBy;
// If no sort order is specified, uses the default
if (TextUtils.isEmpty(sortOrder)) {
orderBy = Memo.DEFAULT_SORT_ORDER;
} else {
// otherwise, uses the incoming sort order
orderBy = sortOrder;
}
// Opens the database object in "read" mode, since no writes need to be done.
SQLiteDatabase db = dbHelper.getReadableDatabase();
/*
* Performs the query. If no problems occur trying to read the database, then a Cursor
* object is returned; otherwise, the cursor variable contains null. If no records were
* selected, then the Cursor object is empty, and Cursor.getCount() returns 0.
*/
Cursor c = qb.query(
db, // The database to query
projection, // The columns to return from the query
selection, // The columns for the where clause
selectionArgs, // The values for the where clause
null, // don't group the rows
null, // don't filter by row groups
orderBy // The sort order
);
// Tells the Cursor what URI to watch, so it knows when its source data changes
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int delete(Uri arg0, String arg1, String[] arg2) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getType(Uri arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri arg0, ContentValues arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
// TODO Auto-generated method stub
return 0;
}
}
Android开发:为应用程序自定义ContentProvider对象以(3)
内容版权声明:除非注明,否则皆为本站原创文章。