當你想提供下列功能時就需要適合使用Content Provider:
a. 將資料或檔案提供給其他App。
b. 讓使用者從你的App複製資料到其他App。
c. 使用搜尋架構提供自訂搜尋建議。
d. 想要將資料給widgets使用
e. 想要使用 AbstractThreadedSyncAdapter, CursorAdapter, 或CursorLoader

在資料提供上有兩種型式
a. 檔案資料File data
像是你app內私有空間的檔案, 像是照片, 音樂或是影像
b. 結構性資料 Structured data
通常會存在SQLite中, 也可以存在其他的儲存空間

 

以下就介紹簡單的用法

 

1. 官網https://developer.android.com/guide/topics/providers/content-provider-creating.html

01.png

 

2. 在Manifiest內要宣告Provider

ex:

<provider
android:authorities="rx.com.application"
android:name=".database.DbProvider"
android:exported="false" />

02.png

 

3. 要定義相對的URI

public static final Uri CONTENT_URI = new Uri.Builder()
.scheme(SCHEME)
.authority(AUTHORITY)
.appendPath(TABLE_NAME).build();

其中SCHEME就是"content"
AUTHORITY是package
Path則是填對應的Table名稱

03.png

 

4. 接著建立一個class繼承ContentProvider

04.png

 

5. 然後implements 內部的方法

05.png

 

6. 一開始要先訓練路徑, 也就是利用UriMatcher來設定回傳值

ex:

private UriMatcher buildUriMatcher() {
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, TABLE_NAME, URI_RECORD);
return uriMatcher;
}

06.png

 

7. 設定好之後, 在onCreate取得DB和初始化UriMatcher

07.png

 

8. 然後實踐insert的方法, 主要還是實踐DB的insert, 然後回傳Uri即可

long id;
switch (uriMatcher.match(uri)) {
case URI_RECORD:
id = dbManager.insert(TABLE_NAME, contentValues);
break;
default:
throw new UnsupportedOperationException("Uri doesn't match any defined Uris on insert");
}
if (id != -1){
return ContentUris.withAppendedId(uri, id);
}
return null;

08.png

 

9. query則是利用DB的Query來查詢

只是單筆時要判斷寫入Query的where條件

然後回傳Cursor

Cursor cursor = null;
switch (uriMatcher.match(uri)) {
case URI_RECORD_WITH_ID:
selection = (selection != null) ? " AND " + selection : "";
selection = _ID + " = "+ ContentUris.parseId(uri) + selection;
case URI_RECORD:
cursor = dbManager.query(TABLE_NAME, projection, selection, selectionArgs, sortOrder);
break;
default:
throw new UnsupportedOperationException("Uri doesn't match any defined Uris on insert");
}
return cursor;

09.png

 

10. delete也是單純的實踐DB的delete即可

int rowsAffected = 0;
switch (uriMatcher.match(uri)) {
case URI_RECORD:
rowsAffected = dbManager.delete(TABLE_NAME, selection, selectionArgs);
break;
default:
throw new UnsupportedOperationException("Uri doesn't match any defined Uris on delete");
}
return rowsAffected;

10.png

 

11. 最後update也是一樣

int rowsAffected = 0;
switch (uriMatcher.match(uri)) {
case URI_RECORD:
rowsAffected = dbManager.update(TABLE_NAME, value, selection, selectionArgs);
break;
default:
throw new UnsupportedOperationException("Uri doesn't match any defined Uris on delete");
}
return rowsAffected;

11.png  

 

最後使用時只要用

getContentResolver().對應的method就可以了

 

 

arrow
arrow
    文章標籤
    Android Content Provider
    全站熱搜

    RX1226 發表在 痞客邦 留言(0) 人氣()