而使用ContentProvider共享数据的好处是统一了数据访问方式。
当应用需要通过ContentProvider对外共享数据时,第一步需要继承ContentProvider并重写下面方法:
第二步需要在AndroidManifest.xml使用<provider>对该ContentProvider进行配置,为了能让其他应用找到该ContentProvider , ContentProvider 采用了authorities(主机名/域名)对它进行唯一标识,你可以把ContentProvider看作是一个网站(),authorities 就是他的域名:
这个网站以固定的Uri对外提供服务;而ContentResolver则可以当成Android系统内部的HttpClient,它可以指定Uri发送“请求”(实际是调用ContentResolver的方法),这种请求最后委托给ContentProvider处理,从而实现对“网站”(即ContentProvider)内部数据的操作。
<manifest .... >
<application android:icon="@drawable/icon" android:label="@string/app_name">
<provider android:name=".PersonContentProvider" android:authorities="com.bu3g.provider.personprovider"/>
</application>
</manifest>)(想想,网站也是提供数据者),authorities 就是他的域名:
<manifest .... >
<application android:icon="@drawable/icon" android:label="@string/app_name">
<provider android:name=".PersonContentProvider" android:authorities="com.bu3g.provider.personprovider"/>
</application>
</manifest>
public class Activity01 extends Activity
{
/** Called when the activity is first created. */
@Override
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, "NOTENOTE1");
getContentResolver().insert(NotePad.Notes.CONTENT_URI, values);
values.clear();
values.put(NotePad.Notes.TITLE, "title2");
values.put(NotePad.Notes.NOTE, "NOTENOTE2");
getContentResolver().insert(NotePad.Notes.CONTENT_URI, values);
/* 显示 */
displayNote();
}
private void displayNote()
{
String columns[] = new String[] { NotePad.Notes._ID,
NotePad.Notes.TITLE,
NotePad.Notes.NOTE,
NotePad.Notes.CREATEDDATE,
NotePad.Notes.MODIFIEDDATE };
Uri myUri = NotePad.Notes.CONTENT_URI;
Cursor cur = managedQuery(myUri, columns, null, null, null);
if (cur.moveToFirst())
{
String id = null;
String title = null;
do
{
id = cur.getString(cur.getColumnIndex(NotePad.Notes._ID));
title = cur.getString(cur.getColumnIndex(NotePad.Notes.TITLE));
Toast toast=Toast.makeText(this, "TITLE:"+id + "NOTE:" + title, Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 40);
toast.show();
}
while (cur.moveToNext());
}
}
}
public class NotePad {
// ContentProvider的uri
public static final String AUTHORITY = "com.google.provider.NotePad";
private NotePad() {
}
// 定义基本字段
public static final class Notes implements BaseColumns {
private Notes() {
}
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";
public static final String DEFAULT_SORT_ORDER = "modified DESC";
// 字段
public static final String TITLE = "title";
public static final String NOTE = "note";
public static final String CREATEDDATE = "created";
public static final String MODIFIEDDATE = "modified";
}
}
public class NotePadProvider extends ContentProvider
{
private static final String TAG = "NotePadProvider";
// 数据库名
private static final String DATABASE_NAME = "note_pad.db";
private static final int DATABASE_VERSION = 2;
// 表名
private static final String NOTES_TABLE_NAME = "notes";
private static HashMap<String, String> sNotesProjectionMap;
private static final int NOTES = 1;
private static final int NOTE_ID = 2;
private static final UriMatcher sUriMatcher;
private DatabaseHelper mOpenHelper;
//创建表SQL语句
private static final String CREATE_TABLE="CREATE TABLE "
+ NOTES_TABLE_NAME
+ " (" + Notes._ID
+ " INTEGER PRIMARY KEY,"
+ Notes.TITLE
+ " TEXT,"
+ Notes.NOTE
+ " TEXT,"
+ Notes.CREATEDDATE
+ " INTEGER,"
+ Notes.MODIFIEDDATE
+ " INTEGER" + ");";
static
{
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(NotePad.AUTHORITY, "notes", NOTES);
sUriMatcher.addURI(NotePad.AUTHORITY, "notes/#", NOTE_ID);
sNotesProjectionMap = new HashMap<String, String>();
sNotesProjectionMap.put(Notes._ID, Notes._ID);
sNotesProjectionMap.put(Notes.TITLE, Notes.TITLE);
sNotesProjectionMap.put(Notes.NOTE, Notes.NOTE);
sNotesProjectionMap.put(Notes.CREATEDDATE, Notes.CREATEDDATE);
sNotesProjectionMap.put(Notes.MODIFIEDDATE, Notes.MODIFIEDDATE);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
//构造函数-创建数据库
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//创建表
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_TABLE);
}
//更新数据库
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
@Override
public boolean onCreate()
{
mOpenHelper = new DatabaseHelper(getContext());
return true;
}
@Override
//查询操作
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
{
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
switch (sUriMatcher.match(uri))
{
case NOTES:
qb.setTables(NOTES_TABLE_NAME);
qb.setProjectionMap(sNotesProjectionMap);
break;
case NOTE_ID:
qb.setTables(NOTES_TABLE_NAME);
qb.setProjectionMap(sNotesProjectionMap);
qb.appendWhere(Notes._ID + "=" + uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
String orderBy;
if (TextUtils.isEmpty(sortOrder))
{
orderBy = NotePad.Notes.DEFAULT_SORT_ORDER;
}
else
{
orderBy = sortOrder;
}
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
// 如果有自定义类型,必须实现该方法
public String getType(Uri uri)
{
switch (sUriMatcher.match(uri))
{
case NOTES:
return Notes.CONTENT_TYPE;
case NOTE_ID:
return Notes.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
//插入数据库
public Uri insert(Uri uri, ContentValues initialValues)
{
if (sUriMatcher.match(uri) != NOTES)
{
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (initialValues != null)
{
values = new ContentValues(initialValues);
}
else
{
values = new ContentValues();
}
Long now = Long.valueOf(System.currentTimeMillis());
if (values.containsKey(NotePad.Notes.CREATEDDATE) == false)
{
values.put(NotePad.Notes.CREATEDDATE, now);
}
if (values.containsKey(NotePad.Notes.MODIFIEDDATE) == false)
{
values.put(NotePad.Notes.MODIFIEDDATE, now);
}
if (values.containsKey(NotePad.Notes.TITLE) == false)
{
Resources r = Resources.getSystem();
values.put(NotePad.Notes.TITLE, r.getString(android.R.string.untitled));
}
if (values.containsKey(NotePad.Notes.NOTE) == false)
{
values.put(NotePad.Notes.NOTE, "");
}
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
long rowId = db.insert(NOTES_TABLE_NAME, Notes.NOTE, values);
if (rowId > 0)
{
Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(noteUri, null);
return noteUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
@Override
//删除数据
public int delete(Uri uri, String where, String[] whereArgs)
{
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri))
{
case NOTES:
count = db.delete(NOTES_TABLE_NAME, where, whereArgs);
break;
case NOTE_ID:
String noteId = uri.getPathSegments().get(1);
count = db.delete(NOTES_TABLE_NAME, Notes._ID + "=" + noteId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
//更新数据
public int update(Uri uri, ContentValues values, String where, String[] whereArgs)
{
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri))
{
case NOTES:
count = db.update(NOTES_TABLE_NAME, values, where, whereArgs);
break;
case NOTE_ID:
String noteId = uri.getPathSegments().get(1);
count = db.update(NOTES_TABLE_NAME, values, Notes._ID + "=" + noteId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
}