創(chuàng)建自己的內(nèi)容提供器

1.創(chuàng)建自己的內(nèi)容提供器

?新建MyProvider類繼承ContentProvider:
??New---Other---ContentProvider

public class MyProvider extends ContentProvider {
    public MyProvider() {
        
    }

    @Override
    public boolean onCreate() {
        //初始化內(nèi)容提供器的時候調(diào)用。
        // 通常會在這里完成對數(shù)據(jù)庫的創(chuàng)建和升級等操作
        //返回true表示內(nèi)容提供器初始化成功,false表示失敗
        return false;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        //返回查詢結(jié)果
        return null;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        //根據(jù)傳入的內(nèi)容URI來返回相應(yīng)的MIME類型
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        //添加完成后,返回一個用于表示這條新記錄的URI
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        //返回被刪除的行數(shù)
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        //返回更新的行數(shù)
        return 0;
    }
}

?以query()方法為例。在query方法中,根據(jù)傳入的內(nèi)容URI,來匹配期望調(diào)用的表以及表中的數(shù)據(jù)。根據(jù)不同的數(shù)據(jù),編寫不同的方法

?內(nèi)容URI主要分為兩種:
?以路徑結(jié)尾表示期望訪問表中的所有數(shù)據(jù)content://com.futuring.app.sharedata/table
?以id(主鍵)結(jié)尾表示訪問該表中擁有相應(yīng)id的數(shù)據(jù)content://com.futuring.app.sharedata/table/1

?可以使用通配符的方式來分別匹配這兩種格式的內(nèi)容URI
?一個能夠匹配任意表的內(nèi)容URI格式可以寫成:content://com.futuring.app.sharedata/ *
?一個能匹配table表中任意一行數(shù)據(jù)的內(nèi)容URI格式可以寫成:
content://com.futuring.app.sharedata/table/#

?接著利用UriMatcher這個類來實(shí)現(xiàn)匹配內(nèi)容URI的功能。UriMatcher中提供了一個addURI()方法,分別接收內(nèi)容URI的authoritypath,還有一個自定義代碼
?當(dāng)調(diào)用UriMatcher的match()方法時,傳入一個Uri對象返回值是可以與之匹配的自定義代碼,利用這個自定義代碼,就可以判斷出調(diào)用哪張表中的數(shù)據(jù)


?getType()方法用于獲取Uri對象所對應(yīng)的MIME類型。一個內(nèi)容URI所對應(yīng)的MIME主要由3部分組成

  1. 必須以vnd開頭
  2. 如果內(nèi)容URI以路徑結(jié)尾,則后接android.cursor.dir/;如果以id結(jié)尾,則后接android.cursor.item/
  3. 最后接上vnd.<authority>.<path>

?所以對于content://com.futuring.app.sharedata/table這個內(nèi)容URI對應(yīng)的MIME類型:vnd.android.cursor.dir/vnd.com.futuring.app.sharedata.table
?對于content://com.futuring.app.sharedata/table/1這個內(nèi)容URI對應(yīng)的MIME類型:vnd.android.cursor.item/vnd.com.futuring.app.sharedata.table

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容