編輯:關於 Android 程式設計
ContentProvider 從字面理解就是「內容提供者」,它的作用是作為一座橋梁,讓一個應用的資料(如 SQLiteDatabase、SharedPreferences、Xml、Txt 等)能夠被其他應用存取。
當應用繼承 ContentProvider 類別並重寫提供與存儲資料的方法後,就能向其他應用共享資料。雖然也可用其他方式對外共享資料,但存取方式會因存儲方式而異——用檔案共享就得做檔案讀寫,用 SharedPreferences 就得用其 API。而 ContentProvider 的好處,在於統一了資料存取方式。
Uri 代表要操作的資料,主要包含兩部分資訊:要操作哪個 ContentProvider,以及對其中的什麼資料進行操作。一個 Uri 由以下幾部分組成:
1. scheme:ContentProvider 的 scheme 已由 Android 規定為 content://。
2. 主機名(Authority):唯一標識這個 ContentProvider,外部呼叫者可據此找到它。
3. 路徑(path):用來表示要操作的資料,可依業務構建。例如操作 contact 表中 id 為 10 的記錄可寫成 /contact/10;操作所有記錄則寫成 /contact。要操作的資料也不一定來自資料庫,例如操作 xml 檔中 contact 節點下的 name 節點可寫成 /contact/name。
把字串轉成 Uri 可使用 Uri.parse(),例如:
Uri uri = Uri.parse("content://com.figo.helloworld.MyContentProvider/contacter")由於 Uri 代表要操作的資料,我們經常需要解析 Uri。Android 提供了兩個工具類別:
UriMatcher:用於匹配 Uri。先把需要匹配的路徑全部註冊上去,再以 match() 比對,命中就返回註冊時傳入的匹配碼。
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI("content://com.figo.helloworld.MyContentProvider/contacter", "contacter", 1); uriMatcher.addURI("content://com.figo.helloworld.MyContentProvider", "contacter /#", 2);//#為通配符ContentUris:用於取得 Uri 路徑後面的 ID 部分。withAppendedId(uri, id) 為路徑加上 ID,parseId(uri) 則從路徑中取出 ID。
ContentResolver:外部應用要對 ContentProvider 中的資料進行增刪改查時,可使用 ContentResolver,透過 Activity 的 getContentResolver() 取得,再呼叫 insert、delete、update、query 等方法操作資料。
本實例在 helloworld 應用中建立一個名為 contacter 的 SQLite 資料庫,裡面有一張 contacter 表,包含 contacterid、name、age 三個欄位。接著透過 ContentProvider 實現對資料的增刪改查,並用 GridView 展示;最後在另一個應用 Sudoku 中,透過 helloworld 提供的 ContentProvider 操作同一份資料,實現跨應用的資料共享。
第一步:新建頁面 contentproviderview.xml 與 friendview.xml。
第二步:新建 SQLiteOpenHelper
package com.figo.helloworld; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class MySQLiteOpenHelper extends SQLiteOpenHelper { private static final String SQLITE_NAME = "contacter"; private static final int version = 1; public MySQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } public MySQLiteOpenHelper(Context context) { super(context, SQLITE_NAME, null, version); } @Override public void onCreate(SQLiteDatabase arg0) { arg0.execSQL("CREATE TABLE contacter (contacterid integer primary key autoincrement,name varchar(20),age INTEGER)"); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { arg0.execSQL("DROP TABLE IF EXISTS contacter"); onCreate(arg0); } }第三步:新建 ContentProvider,重寫 delete、getType、insert、onCreate、query、update 等方法,並依 Uri 匹配結果分別處理「全部記錄」與「單筆記錄」兩種情況。
package com.figo.helloworld; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.text.TextUtils; public class MyContentProvider extends ContentProvider { private MySQLiteOpenHelper mySQLiteOpenHelper; private final static int CONTACTER = 1; private final static int CONTACTERS = 2; private final static String AUTHORITY = "com.figo.helloworld.MyContentProvider"; private static final UriMatcher pMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { pMatcher.addURI(AUTHORITY, "contacter", CONTACTERS); pMatcher.addURI(AUTHORITY, "contacter/#", CONTACTER); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase(); int count = 0; switch (pMatcher.match(uri)) { case CONTACTERS: count = db.delete("contacter", selection, selectionArgs); break; case CONTACTER: long sid = ContentUris.parseId(uri); String where = TextUtils.isEmpty(selection) ? "contacterid=?" : selection + " and contacterid=?"; String[] params = new String[] { String.valueOf(sid) }; count = db.delete("contacter", where, params); break; default: throw new IllegalArgumentException("Unknow Uri: " + uri); } return count; } @Override public String getType(Uri uri) { switch (pMatcher.match(uri)) { case CONTACTERS: return "vnd.android.cursor.dir/MyContentProvider.contacter"; case CONTACTER: return "vnd.android.cursor.item/MyContentProvider.contacter"; default: throw new IllegalArgumentException("Unknow Uri: " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase(); long pid = 0; switch (pMatcher.match(uri)) { case CONTACTERS: pid = db.insert("contacter", "name", values); return ContentUris.withAppendedId(uri, pid); default: throw new IllegalArgumentException("Unknow Uri: " + uri); } } @Override public boolean onCreate() { mySQLiteOpenHelper = new MySQLiteOpenHelper(this.getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase(); switch (pMatcher.match(uri)) { case CONTACTERS: return db.query("contacter", projection, selection, selectionArgs, null, null, sortOrder); case CONTACTER: long pid = ContentUris.parseId(uri); String where = TextUtils.isEmpty(selection) ? "contacterid=?" : selection + " and contacterid=?"; String[] params = new String[] { String.valueOf(pid) }; return db.query("contacter", projection, where, params, null, null, sortOrder); default: throw new IllegalArgumentException("Unknow Uri: " + uri); } } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase(); int count = 0; switch (pMatcher.match(uri)) { case CONTACTERS: count = db.update("contacter", values, selection, selectionArgs); break; default: throw new IllegalArgumentException("Unknow Uri: " + uri); } return count; } }第四步:新建 Activity,透過 getContentResolver() 取得 ContentResolver,並為增刪改查按鈕加上事件;查詢結果以 SimpleAdapter 綁定到 GridView 展示。
Uri uri = Uri.parse("content://com.figo.helloworld.MyContentProvider/contacter"); // 增: resolver.insert(uri, cvadd); // 刪: resolver.delete(uri, "contacterid=?", deleteparas); // 改: resolver.update(uri, cvupdate, "contacterid=?", updateparas); // 查: Cursor cursor = resolver.query(uri, new String[]{"contacterid","name","age"}, null, null, "contacterid desc");第五步:在 AndroidManifest.xml 註冊 MyContentProvider 與 ContentProviderActivity。

在 helloworld 應用中安裝完成後,Sudoku 應用只要把 ContentProviderActivity.java、contentproviderview.xml、friendview.xml 複製過來,透過 getContentResolver() 取得 helloworld 暴露出來的 MyContentProvider,就能直接操作 helloworld 裡的資料了。可見當一個應用需要向另一個應用暴露資料時,ContentProvider 是非常方便的選擇。
從零開始搭建 Android 開發環境:JDK、SDK、ADT 與 AVD 完整流程
要開始寫 Android 程式,第一道門檻就是把開發環境搭起來。整個過程大致可以拆成四個階段:確認 JDK、下載 SDK、安裝 ADT、建立 AVD(Android 虛擬
Android 以 XML 打造動畫介面的完整解析
以 XML 建立動畫的基本流程在 Android 中,若希望介面具有淡入、淡出、縮放或旋轉等效果,可先在 res 下手動建立 anim 資料夾,將動畫定義寫成 XML 檔
小米手機用久了變卡?六個讓它重新跑順的實用設定
小米在國內的普及率相當高,但用上一段時間之後,不少使用者會發現手機變慢、開機變久。這其實多半不是硬體老化,而是啟動項與背景程序累積太多。以下幾個調整方向,做完之後速度會明
Service 的工作過程:啟動與綁定的源碼全流程剖析
Service 有兩種工作狀態:一種是啟動狀態,主要用於後台計算;另一種是綁定狀態,主要用於與其他組件交互。兩者並不互斥,一個 Service 完全可以同時處於啟動與綁定