工程1自定义ContentProvider:
NotePad.java:
public class NotePad
{
//ContentProvider的uri
public static final String AUTHORITY = "com.google.provider.csqNotePad";
//BaseColumns是一个常量接口,里面有一个"_id和"_count"字符串常量
public static class Notes implements BaseColumns
{
//访问URI
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/notes");
// 内容类型,新的MIME类型-多个
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.note";
// 新的MIME类型-单个
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.note";
//默认排序常量,按id排序
public static final String DEFAULT_SORT_ORDER = "_id DESC";
//字段
public static final String TITLE = "title";
public static final String NOTE = "note";
}
}
MyProvider.java:
public class MyProvider extends ContentProvider
{
private DatabaseHelper mOpenHelper = null;
private static final UriMatcher sUriMatcher;
private static HashMap<String, String> sNotesProjectionMap;
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(NotePad.AUTHORITY, "notes", 1);
sUriMatcher.addURI(NotePad.AUTHORITY, "notes/#", 2);
sNotesProjectionMap = new HashMap<String, String>();
sNotesProjectionMap.put(NotePad.Notes._ID, NotePad.Notes._ID);
sNotesProjectionMap.put(NotePad.Notes.TITLE, NotePad.Notes.TITLE);
sNotesProjectionMap.put(NotePad.Notes.NOTE, NotePad.Notes.NOTE);
}
// 数据库名
private static final String DATABASE_NAME = "cptest.db";
private static final int DATABASE_VERSION = 2;
// 表名
private static final String NOTES_TABLE_NAME = "notes";
// 创建表SQL语句
private static final String
CREATE_TABLE = "CREATE TABLE " + NOTES_TABLE_NAME + " (" + NotePad.Notes._ID
+ " INTEGER PRIMARY KEY," + NotePad.Notes.TITLE + " TEXT," + NotePad.Notes.NOTE
+ " TEXT" + ");";
//内部类SQLiteOpenHelper
private static class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
//创建
public boolean onCreate()
{
mOpenHelper = new DatabaseHelper(getContext());
return true;
}
// 查询操作
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder)
{
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
switch (sUriMatcher.match(uri))
{
case 1://notes,所有
qb.setTables(NOTES_TABLE_NAME);
qb.setProjectionMap(sNotesProjectionMap);
break;
case 2://notes/#,根据id查询
qb.setTables(NOTES_TABLE_NAME);
qb.setProjectionMap(sNotesProjectionMap);
qb.appendWhere(NotePad.Notes._ID + "=" + uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
//排序方式
String orderBy;
if (sortOrder == null) {
orderBy = NotePad.Notes.DEFAULT_SORT_ORDER;
} else {
orderBy = sortOrder;
}
//获取数据库实例
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
//返回游标集合
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
// 插入数据库
public Uri insert(Uri uri, ContentValues initialValues)
{
if (sUriMatcher.match(uri) != 1)
{
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues cv;
if (initialValues != null)
{
cv = new ContentValues(initialValues);
} else {
cv = new ContentValues();
}
if (cv.containsKey(NotePad.Notes.TITLE) == false)
{
Resources r = Resources.getSystem();
cv.put(NotePad.Notes.TITLE,
r.getString(android.R.string.untitled));
}
if (cv.containsKey(NotePad.Notes.NOTE) == false)
{
cv.put(NotePad.Notes.NOTE, "");
}
//获取数据库实例
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
//插入数据,返回id
long rowId = db.insert(NOTES_TABLE_NAME, NotePad.Notes.NOTE, cv);
//如果成功插入返回uri
if (rowId > 0)
{
Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI,rowId);
getContext().getContentResolver().notifyChange(noteUri, null);
return noteUri;
}
return null;
}
//删除数据
public int delete(Uri uri, String where, String[] whereArgs)
{
//获取数据库实例
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
//根据指定条件删除
switch (sUriMatcher.match(uri))
{
case 1:
count = db.delete(NOTES_TABLE_NAME, where, whereArgs);
break;
case 2:
String noteId = uri.getPathSegments().get(1);
count = db.delete(NOTES_TABLE_NAME,
NotePad.Notes._ID + "=" + noteId + (!where.isEmpty() ? " AND (" + where+ ")" : ""),
whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
// 更新数据
public int update(Uri uri, ContentValues values, String where, String[] whereArgs)
{
//获取数据库实例
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
//根据指定条件更新
switch (sUriMatcher.match(uri))
{
case 1:
count = db.update(NOTES_TABLE_NAME, values, where, whereArgs);
break;
case 2:
String noteId = uri.getPathSegments().get(1);
count = db.update(NOTES_TABLE_NAME, values,
NotePad.Notes._ID + "=" + noteId + (!where.isEmpty() ? " AND (" + where
+ ")" : ""),
whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
// 如果有自定义类型,必须实现该方法
public String getType(Uri uri)
{
switch (sUriMatcher.match(uri))
{
case 1:
return NotePad.Notes.CONTENT_TYPE;
case 2:
return NotePad.Notes.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
}
在AndroidMainfest.xml中声明:
<provider android:name = "MyProvider"
android:authorities = "com.google.provider.csqNotePad"/>
在此工程Activity中测试:
public class MainActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* 插入数据 */
ContentValues values = new ContentValues();
values.put(NotePad.Notes.TITLE, "title1");
values.put(NotePad.Notes.NOTE, "note1");
getContentResolver().insert(NotePad.Notes.CONTENT_URI, values);
values.clear();
values.put(NotePad.Notes.TITLE, "title2");
values.put(NotePad.Notes.NOTE, "note2");
getContentResolver().insert(NotePad.Notes.CONTENT_URI, values);
/* 显示 */
displayNote();
Log.i("displayNote", "****************************************");
updateFirst();
displayNote();
Log.i("displayNote", "****************************************");
deleteFirst();
displayNote();
Log.i("displayNote", "****************************************");
}
private void displayNote()
{
String[] columns = new String[] { NotePad.Notes._ID,
NotePad.Notes.TITLE,
NotePad.Notes.NOTE,
};
Uri myUri = NotePad.Notes.CONTENT_URI;
Cursor cur = managedQuery(myUri, columns, null, null, null);
for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(NotePad.Notes._ID));
String title = cur.getString(cur.getColumnIndex(NotePad.Notes.TITLE));
String note = cur.getString(cur.getColumnIndex(NotePad.Notes.NOTE));
Log.i("displayNote", "id="+id+", title="+title+", note="+note);
}
}
private void updateFirst()
{
ContentValues values = new ContentValues();
values.put(NotePad.Notes.TITLE, "update1");
values.put(NotePad.Notes.NOTE, "updatenote1");
getContentResolver().update(NotePad.Notes.CONTENT_URI, values, NotePad.Notes._ID +"=1", null);
}
private void deleteFirst()
{
ContentValues values = new ContentValues();
values.put(NotePad.Notes.TITLE, "update1");
values.put(NotePad.Notes.NOTE, "updatenote1");
getContentResolver().delete(NotePad.Notes.CONTENT_URI, NotePad.Notes._ID +"=1", null);
}
}
新建一工程,在工程外调用:
需要权限:
<uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
测试程序:
public class MainActivity extends Activity
{
Uri uri = Uri.parse("content://com.google.provider.csqNotePad/notes");
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* 插入数据 */
ContentValues values = new ContentValues();
values.put("title", "title1");
values.put("note", "note1");
getContentResolver().insert(uri, values);
values.clear();
values.put("title", "title2");
values.put("note", "note2");
getContentResolver().insert(uri, values);
/* 显示 */
displayNote();
Log.i("displayNote", "****************************************");
updateFirst();
displayNote();
Log.i("displayNote", "****************************************");
deleteFirst();
displayNote();
Log.i("displayNote", "****************************************");
}
private void displayNote()
{
String[] columns = new String[] { "_id", "title", "note"};
Cursor cur = managedQuery(uri, columns, null, null, null);
for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex("_id"));
String title = cur.getString(cur.getColumnIndex("title"));
String note = cur.getString(cur.getColumnIndex("note"));
Log.i("displayNote", "id="+id+", title="+title+", note="+note);
}
}
private void updateFirst()
{
ContentValues values = new ContentValues();
values.put("title", "update1");
values.put("note", "updatenote1");
getContentResolver().update(uri, values, "title = 'title1'", null);
}
private void deleteFirst()
{
getContentResolver().delete(uri, "title = 'update1'", null);
}
}