內容提供者

一、ContentProvider簡介

    當應用繼承ContentProvider類,並重寫該類用於提供數據和存儲數據的方法,就可以向其他應用共享其數據。ContentProvider爲存儲和獲取數據提供了統一的接口。雖然使用其他方法也可以對外共享數據,但數據訪問方式會因數據存儲的方式而不同,如採用文件方式對外共享數據,需要進行文件操作讀寫數據;採用sharedpreferences共享數據,需要使用sharedpreferences API讀寫數據。而使用ContentProvider共享數據的好處是統一了數據訪問方式。

    

    query(Uri uri, String[] projection, String selection, String[] selectionArgs,String sortOrder)

        通過Uri進行查詢,返回一個Cursor

    insert(Uri url, ContentValues values)

        將一組數據插入到Uri 指定的地方

    update(Uri uri, ContentValues values, String where, String[] selectionArgs)

        更新Uri指定位置的數據

    delete(Uri url, String where, String[] selectionArgs)

        刪除指定Uri並且符合一定條件的數據

 

 

二、Uri類簡介

    Uri代表了要操作的數據,Uri主要包含了兩部分信息

    ①需要操作的ContentProvider

    ②對ContentProvider中的什麼數據進行操作

    

    組成部分

    ①scheme:ContentProvider的scheme已經由Android所規定爲content://

    ②主機名(Authority):用於唯一標識這個ContentProvider,外部調用者可以根據這個標識來找到它。建議爲公司域名,保持唯一性

    ③路徑(path):可以用來表示我們要操作的數據,路徑的構建應根據業務而定:

    

    要操作person表中id爲10的記錄

    content://cn.xyCompany.providers.personProvider/person/10

    

    要操作person表中id爲10的記錄的name字段

    content://cn.xyCompany.providers.personProvider/person/10/name

    

    要操作person表中的所有記錄

    content://cn.xyCompany.providers.personProvider/person

    

    要操作的數據不一定來自數據庫,也可以是文件等他存儲方式,如要操作xml文件中user節點下的name節點

    content://cn.xyCompany.providers.personProvider/person/10/name

    

    把一個字符串轉換成Uri,可以使用Uri類中的parse()方法

    Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person")

 

三、UriMatcher、ContentUris和ContentResolver簡介

    Uri代表了要操作的數據,所以經常需要解析Uri,並從Uri中獲取數據。Android系統提供了兩個用於操作Uri的工具類,分別爲UriMatcher 和ContentUris。掌握它們的使用會便於我們的開發工作。

    

    UriMatcher

    用於匹配Uri

    ①把需要匹配Uri路徑全部給註冊上

    // 常量UriMatcher.NO_MATCH表示不匹配任何路徑的返回碼(-1)。

    UriMatcher  uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    // 若match()方法匹配content://cn.xyCompany.providers.personProvider/person路徑則返回匹配碼爲1

    uriMatcher.addURI("content://cn.xyCompany.providers.personProvider","person", 1);

    // 若match()方法匹配content://cn.xyCompany.providers.personProvider/person/10路徑則返回匹配碼爲2

    uriMatcher.addURI("content://cn.xyCompany.providers.personProvider","person/#", 1);

    ②註冊完需要匹配的Uri後,就可以使用uriMatcher.match(uri)方法對輸入的Uri進行匹配


    ContentUris

    ContentUris是對URI的操作類,其中的withAppendedId(uri, id)用於爲路徑加上ID部分,parseId(uri)方法用於從路徑中獲取ID部分方法很實用。

        Uri insertUri = Uri.parse("content://cn.xyCompany.providers.personProvider/person" + id);等價於

        Uri insertUri = ContentUris.withAppendedId(uri, id);

        

        Uri uri = Uri.parse("content://cn.xxt.provider.personprovider/person/10")

        long personid = ContentUris.parseId(uri);//獲取的結果爲:10


    ContentResolver

    當外部應用需要對ContentProvider中的數據進行添加、刪除、修改和查詢操作時,可以使用ContentResolver 類來完成。要獲取ContentResolver對象,可以使用Activity提供的getContentResolver()方法。ContentResolver使用insert、delete、update、query方法來操作數據。


三、實例代碼

    當數據需要在應用程序間共享時,我們就可以利用ContentProvider爲數據定義一個URI。之後其他應用程序對數據進行查詢或者修改時,只需要從當前上下文對象獲得一個ContentResolver(內容解析器)傳入相應的URI就可以了。

    contentProvider和Activity一樣是Android的組件,故使用前需要在AndroidManifest.xml中註冊,必須放在主應用所在包或其子包下。


    <application android:icon="@drawable/icon" android:label="@string/app_name">  

        <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>  

            <intent-filter>  

                <data android:mimeType="vnd.android.cursor.dir/person" />  

            </intent-filter>  

            <intent-filter>  

                <data android:mimeType="vnd.android.cursor.item/person" />  

            </intent-filter>  

        </activity>  

        <!-- 配置內容提供者,android:authorities爲該內容提供者取名作爲在本應用中的唯一標識 -->  

        <provider android:name=".providers.PersonProvider" 

            android:authorities="cn.xyCompany.providers.personProvider"/>  

    </application>  

 

內容提供者和測試代碼


    內容提供者  

    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.util.Log;  

    import cn.xy.cotentProvider.service.DBOpeningHelper;  

    

    /** 

    * contentProvider作爲一種組件必須放在應用所在包或其子包下,主要作用是對外共享數據 

    * 測試步驟1:將本項目先部署 

    * 測試步驟2:調用測試方法 

    *  

    */  

    public class PersonProvider extends ContentProvider{  

        private DBOpeningHelper dbHelper;  

        

        // 若不匹配採用UriMatcher.NO_MATCH(-1)返回  

        private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);  

        

        // 匹配碼  

        private static final int CODE_NOPARAM = 1;  

        private static final int CODE_PARAM = 2;  

        

        static  

        {  

            // 對等待匹配的URI進行匹配操作,必須符合cn.xyCompany.providers.personProvider/person格式  

            // 匹配返回CODE_NOPARAM,不匹配返回-1  

            MATCHER.addURI("cn.xyCompany.providers.personProvider", "person", CODE_NOPARAM);  

            

            // #表示數字 cn.xyCompany.providers.personProvider/person/10  

            // 匹配返回CODE_PARAM,不匹配返回-1  

            MATCHER.addURI("cn.xyCompany.providers.personProvider", "person/#", CODE_PARAM);  

        }  

 

        @Override  

        public boolean onCreate()  

        {  

            dbHelper = new DBOpeningHelper(this.getContext());  

            return true;  

        }  

        

        /** 

        * 外部應用向本應用插入數據 

        */  

        @Override  

        public Uri insert(Uri uri, ContentValues values){

            SQLiteDatabase db = dbHelper.getWritableDatabase();  

            switch (MATCHER.match(uri)){

                case CODE_NOPARAM:  

                    // 若主鍵值是自增長的id值則返回值爲主鍵值,否則爲行號,但行號並不是RecNo列  

                    long id = db.insert("person", "name", values);   

                    Uri insertUri = ContentUris.withAppendedId(uri, id);   

                    return insertUri;  

                default:  

                    throw new IllegalArgumentException("this is unkown uri:" + uri);  

            }  

        }  

 

        /** 

        * 外部應用向本應用刪除數據 

        */  

        @Override  

        public int delete(Uri uri, String selection, String[] selectionArgs){  

            SQLiteDatabase db = dbHelper.getWritableDatabase();

            switch (MATCHER.match(uri)){

                case CODE_NOPARAM:  

                    return db.delete("person", selection, selectionArgs); // 刪除所有記錄  

                case CODE_PARAM:  

                    long id = ContentUris.parseId(uri); // 取得跟在URI後面的數字  

                    Log.i("provider", String.valueOf(id));  

                    String where = "id = " + id;  

                    if (null != selection && !"".equals(selection.trim())){

                      where += " and " + selection;

                    }  

                    return db.delete("person", where, selectionArgs);  

                default:  

                    throw new IllegalArgumentException("this is unkown uri:" + uri);  

            }

        }  

 

        /** 

        * 外部應用向本應用更新數據 

        */  

        @Override  

        public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs){  

            SQLiteDatabase db = dbHelper.getWritableDatabase();  

            switch (MATCHER.match(uri)){

                case CODE_NOPARAM:  

                    return db.update("person",values,selection, selectionArgs); // 更新所有記錄  

                case CODE_PARAM:  

                    long id = ContentUris.parseId(uri); // 取得跟在URI後面的數字  

                    String where = "id = " + id;  

                    if (null != selection && !"".equals(selection.trim())){  

                        where += " and " + selection;  

                    }  

                    return db.update("person",values,where,selectionArgs);  

                default:  

                    throw new IllegalArgumentException("this is unkown uri:" + uri);  

            }

        }  

     

        /** 

        * 返回對應的內容類型 

        * 如果返回集合的內容類型,必須以vnd.android.cursor.dir開頭 

        * 如果是單個元素,必須以vnd.android.cursor.item開頭 

        */  

        @Override  

        public String getType(Uri uri){

            switch(MATCHER.match(uri)){  

                case CODE_NOPARAM:  

                    return "vnd.android.cursor.dir/person";  

                case CODE_PARAM:  

                    return "vnd.android.cursor.item/person";  

                default:  

                    throw new IllegalArgumentException("this is unkown uri:" + uri);  

            }

        }  

 

        @Override  

        public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)  

        {  

            SQLiteDatabase db = dbHelper.getReadableDatabase();  

            switch (MATCHER.match(uri)){  

                case CODE_NOPARAM:  

                    return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);  

                case CODE_PARAM:  

                    long id = ContentUris.parseId(uri); // 取得跟在URI後面的數字  

                    String where = "id = " + id;  

                    if (null != selection && !"".equals(selection.trim())){  

                        where += " and " + selection;  

                    }  

                    return db.query("person", projection, where, selectionArgs, null, null, sortOrder);  

                default:  

                    throw new IllegalArgumentException("this is unkown uri:" + uri);  

            }  

        }

}  

  

    測試代碼  

    import android.content.ContentResolver;  

    import android.content.ContentValues;  

    import android.database.Cursor;  

    import android.net.Uri;  

    import android.test.AndroidTestCase;  

    import android.util.Log;  

    

    /** 

    * 測試代碼 

    */  

    public class TestProviders extends AndroidTestCase{  

        // 在執行該測試方法時需要先將還有內容提供者的項目部署到Android中,否則無法找到內容提供者  

        public void testInsert(){  

            Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person");  

            ContentResolver resolver = this.getContext().getContentResolver();  

            ContentValues values = new ContentValues();  

            values.put("name", "xy");  

            values.put("phone", "111");  

            resolver.insert(uri, values); // 內部調用內容提供者的insert方法  

        }  

 

        // 不帶id參數的刪除  

        public void testDelete1(){  

            Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person");  

            ContentResolver resolver = this.getContext().getContentResolver();  

            int rowAffect = resolver.delete(uri, null, null);  

            Log.i("rowAffect", String.valueOf(rowAffect));  

        }  

 

        // 帶參數的刪除,通過URI傳遞了id至contentProvider並可追加其他條件  

        public void testDelete2(){  

            Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person/18");  

            ContentResolver resolver = this.getContext().getContentResolver();  

            int rowAffect = resolver.delete(uri, "name = ?", new String[] { "XY2" }); // 在provider中手動進行了拼裝  

            Log.i("rowAffect", String.valueOf(rowAffect));  

        }  

     

        public void testUpdate(){  

            Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person/19");  

            ContentResolver resolver = this.getContext().getContentResolver();  

            ContentValues values = new ContentValues();  

            values.put("name", "newxy");  

            values.put("phone", "new111");  

            int rowAffect = resolver.update(uri, values, null, null);  

            Log.i("rowAffect", String.valueOf(rowAffect));  

        }  

     

        public void testQuery(){  

            Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person/19");  

            ContentResolver resolver = this.getContext().getContentResolver();  

            Cursor cursor = resolver.query(uri, new String[]{"id","name","phone"}, null, null, "id asc");  

            if(cursor.moveToFirst()){  

                Log.i("query", cursor.getString(cursor.getColumnIndex("name")));  

            }  

            cursor.close();  

        }

    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章