編輯:關於 Android 程式設計
ContentProvider 是 Android 四大元件之一,也是跨應用程式共享資料的唯一標準途徑。它的核心職責是儲存與擷取資料,並向其他應用程式提供存取介面。系統本身已為常見資料型別(音樂、影片、圖片、聯絡人資訊等)內建了一系列 Provider,位於 android.provider 套件下,持有適當權限即可存取。
ContentProvider 以資料表的形式對外呈現資料:每一列是一筆紀錄,每一欄是具有特定型別與意義的資料。每筆紀錄都包含一個 _ID 欄位,用於唯一標識該筆資料——這是 Android 的慣例,CursorAdapter 等元件都依賴它。
每個 ContentProvider 都對外提供一個能唯一標識其資料集的公開 URI。若一個 Provider 管理多個資料集,每個資料集會有各自獨立的 URI。所有 URI 都以 content:// 開頭,其中 content: 這個 scheme 就是用來標示「資料由 ContentProvider 管理」。
由於幾乎所有操作都要用到 URI,實務上應把 URI 定義為常數,既簡化開發也提高可維護性。
存取是透過 ContentResolver 物件進行,它提供了查詢、插入、修改、刪除的方法。以查詢為例,你需要掌握三項資訊:
若要存取特定某一筆紀錄,只要知道該筆的 ID 即可。
查詢有兩個入口:ContentResolver.query() 與 Activity.managedQuery(),參數完全相同,回傳的都是 Cursor。差別在生命週期管理:managedQuery() 建立的 Cursor 會由 Activity 代管——Activity 進入暫停狀態時自動呼叫 deactivate() 卸載,回到執行狀態時呼叫 requery() 重新查詢。若想把未經管理的 Cursor 交給 Activity 代管,可呼叫 startManagingCursor()。
以下是一個「員工通訊錄」的完整 CRUD 實作,包含常量定義、Provider、資料庫 Helper 與呼叫端。
把 authority、URI、欄位名稱集中管理,是 ContentProvider 開發的基本功。
package com.amaker.ch10.app;
import android.net.Uri;
import android.provider.BaseColumns;
public final class Employees {
// 授權字串,必須與 Manifest 中的 authorities 一致
public static final String AUTHORITY = "com.amaker.provider.Employees";
private Employees() {}
public static final class Employee implements BaseColumns {
private Employee() {}
// 存取 URI
public static final Uri CONTENT_URI =
Uri.parse("content://" + AUTHORITY + "/employee");
// 內容型別:dir 代表多筆,item 代表單筆
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.amaker.employees";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.amaker.employees";
public static final String DEFAULT_SORT_ORDER = "name DESC";
// 資料表欄位
public static final String NAME = "name";
public static final String GENDER = "gender";
public static final String AGE = "age";
}
}
實作 BaseColumns 即可免費取得 _ID 與 _COUNT 兩個標準欄位常數。
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Employees.db";
private static final int DATABASE_VERSION = 1;
public static final String EMPLOYEES_TABLE_NAME = "employee";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + EMPLOYEES_TABLE_NAME + " ("
+ Employee._ID + " INTEGER PRIMARY KEY,"
+ Employee.NAME + " TEXT,"
+ Employee.GENDER + " TEXT,"
+ Employee.AGE + " INTEGER"
+ ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS employee");
onCreate(db);
}
}
Provider 的核心是 UriMatcher——它負責判斷傳入的 URI 是「整個資料集」還是「某一筆特定資料」,據以決定查詢條件。
public class EmployeeProvider extends ContentProvider {
private DBHelper dbHelper;
private static final UriMatcher sUriMatcher;
private static final int EMPLOYEE = 1; // 全部資料
private static final int EMPLOYEE_ID = 2; // 單筆資料
private static HashMap<String, String> empProjectionMap;
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(Employees.AUTHORITY, "employee", EMPLOYEE);
sUriMatcher.addURI(Employees.AUTHORITY, "employee/#", EMPLOYEE_ID);
empProjectionMap = new HashMap<String, String>();
empProjectionMap.put(Employee._ID, Employee._ID);
empProjectionMap.put(Employee.NAME, Employee.NAME);
empProjectionMap.put(Employee.GENDER, Employee.GENDER);
empProjectionMap.put(Employee.AGE, Employee.AGE);
}
@Override
public boolean onCreate() {
dbHelper = new DBHelper(getContext());
return true;
}
}
注意 employee/# 中的 # 是數字萬用字元,用來比對帶 ID 的 URI。
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
long rowId = db.insert(DBHelper.EMPLOYEES_TABLE_NAME, Employee.NAME, values);
if (rowId > 0) {
Uri empUri = ContentUris.withAppendedId(Employee.CONTENT_URI, rowId);
// 通知監聽者資料已變更
getContext().getContentResolver().notifyChange(empUri, null);
return empUri;
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case EMPLOYEE:
count = db.delete(DBHelper.EMPLOYEES_TABLE_NAME, selection, selectionArgs);
break;
case EMPLOYEE_ID:
String noteId = uri.getPathSegments().get(1);
count = db.delete(DBHelper.EMPLOYEES_TABLE_NAME,
Employee._ID + "=" + noteId
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""),
selectionArgs);
break;
default:
throw new IllegalArgumentException("錯誤的 URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
notifyChange() 是 ContentProvider 有別於一般資料庫操作的關鍵:它讓所有註冊了 ContentObserver 的用戶端能即時收到通知並刷新畫面。
查詢使用 SQLiteQueryBuilder,並在回傳 Cursor 前呼叫 setNotificationUri() 註冊觀察:
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
switch (sUriMatcher.match(uri)) {
case EMPLOYEE:
qb.setTables(DBHelper.EMPLOYEES_TABLE_NAME);
qb.setProjectionMap(empProjectionMap);
break;
case EMPLOYEE_ID:
qb.setTables(DBHelper.EMPLOYEES_TABLE_NAME);
qb.setProjectionMap(empProjectionMap);
qb.appendWhere(Employee._ID + "=" + uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Uri錯誤! " + uri);
}
String orderBy;
if (TextUtils.isEmpty(sortOrder)) {
orderBy = Employee.DEFAULT_SORT_ORDER;
} else {
orderBy = sortOrder;
}
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case EMPLOYEE:
count = db.update(DBHelper.EMPLOYEES_TABLE_NAME, values, selection, selectionArgs);
break;
case EMPLOYEE_ID:
String noteId = uri.getPathSegments().get(1);
count = db.update(DBHelper.EMPLOYEES_TABLE_NAME, values,
Employee._ID + "=" + noteId
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""),
selectionArgs);
break;
default:
throw new IllegalArgumentException("錯誤的 URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
insert();
query();
update();
query();
del();
query();
}
private void insert() {
Uri uri = Employee.CONTENT_URI;
ContentValues values = new ContentValues();
values.put(Employee.NAME, "amaker");
values.put(Employee.GENDER, "male");
values.put(Employee.AGE, 30);
getContentResolver().insert(uri, values);
}
private void query() {
String[] PROJECTION = new String[] {
Employee._ID, // 0
Employee.NAME, // 1
Employee.GENDER, // 2
Employee.AGE // 3
};
Cursor c = managedQuery(Employee.CONTENT_URI, PROJECTION, null,
null, Employee.DEFAULT_SORT_ORDER);
if (c.moveToFirst()) {
for (int i = 0; i < c.getCount(); i++) {
c.moveToPosition(i);
String name = c.getString(1);
String gender = c.getString(2);
int age = c.getInt(3);
Log.i("emp", name + ":" + gender + ":" + age);
}
}
}
private void update() {
Uri uri = ContentUris.withAppendedId(Employee.CONTENT_URI, 1);
ContentValues values = new ContentValues();
values.put(Employee.NAME, "hz.guo");
values.put(Employee.GENDER, "male");
values.put(Employee.AGE, 31);
getContentResolver().update(uri, values, null, null);
}
private void del() {
Uri uri = ContentUris.withAppendedId(Employee.CONTENT_URI, 1);
getContentResolver().delete(uri, null, null);
}
}
ContentUris.withAppendedId() 是組出「帶 ID 的 URI」的標準做法,它會產生 content://.../employee/1 這樣的形式,正好能被 Provider 中的 UriMatcher 比對為 EMPLOYEE_ID。
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.amaker.ch10.app"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<provider android:name="EmployeeProvider"
android:authorities="com.amaker.provider.Employees" />
<activity android:name=".MainActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
android:authorities 必須與 Employees 類別中定義的 AUTHORITY 完全一致,否則 URI 無法解析。
android:exported 與讀寫權限。
Android 智能短信應用實作(二):會話刪除、自定義對話框與簡訊發送
本篇接續短信應用的開發,處理幾個實務上一定會遇到的環節:批次刪除會話、打造可重複使用的自定義對話框、帶進度條的刪除流程、會話詳情頁的資料傳遞與異步載入,以及簡訊的發送。
動手做一個炫酷的 ViewPagerIndicator(不只仿 MIUI)
做 tab 切換時,多數人會直接抓 TabPageIndicator 來用,很多知名 App 也是。但指示器本身的原理並不難,自己寫一遍,之後要改成下劃線樣式也只是幾行的
Android Support Annotations 使用詳解
在 Android Support Library 19.1 版本中,Android 工具小組引進了幾個很實用的註解類型,供開發者在專案中使用,而 Support Lib
Android Studio 怎麼改 JDK 與 SDK 的路徑?一張圖找到設定入口
這個問題對很多剛從 Eclipse 轉到 Android Studio 的人來說確實有點惱人:明明知道有這個選項,但在設定裡翻半天就是找不到它在哪。 原因很簡單——JD