1. 程式人生 > >Contentprovider的基本用法

Contentprovider的基本用法

在前兩年的開發中我們是很少看到ContentProvider的情況,但隨著社會的進步資料化的東西越來越多,進而需要各種資料訪問也就越來越多。android提供了ContentProvider來應對不同應用間的資料訪問。下面我們就對ContentProvider進行一個簡單的用法介紹;

在資料儲存端

  1. 繼承ContentPovider;
  2. AndroidManifest.xml中配置;
  3. 在ContentProvider中匹配訪問地址的正確性;
  4. 得到ContentResolver傳遞過來的引數;(與第6步對應)
  5. 操作資料庫;

資料訪問端;

6.ContentResolver傳遞Uri地址,以及要操縱資料庫CRUD的對應引數給ContentProvider的CRUD方法;(與第3.4步對應)

我們根據上面的思路來一一實現

首先繼承ContentProvider重寫對應的方法;

public class ContentProvideDemo extends ContentProvider {
    private static final String TAG = ContentProvideDemo.class.getSimpleName();

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Log.d(TAG, "query: enter"
); System.out.print("uri = " + uri); return null; } @Override public String getType(Uri uri) { Log.d(TAG, "getType: enter"); return null; } @Override public Uri insert(Uri uri, ContentValues values) { Log.d(TAG, "insert: enter"); return
null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { Log.d(TAG, "delete: enter"); return 0; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { Log.d(TAG, "update: enter"); return 0; } }

AndroidManifest.xml中配置;

<provider
android:name=".ContentProvideDemo"           android:authorities="com.example.concentrated"
android:exported="true"/>
//這裡的authorities相當於協議。
//exported="true"表示能被外界訪問;

在ContentProvider中匹配訪問地址的正確性;

    private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        //為UriMatcher註冊兩個Uri;
        /*
        String authority, 協議也就是AndroidManifaset.xml檔案中配置的authority;
        String path,與authority組成一個uri 這裡都是自己給出的,因為uri的地址是自己建立的;
        int code,code為uri的標示碼;
         */
        matcher.addURI("com.example.concentrated", "words", 6);
        //#號為萬用字元;
        matcher.addURI("com.example.concentrated", "word/#", 3);
        //下面說面下這兩種配法的意思
        /*第一種為標準寫法,為常用狀態。也就是說當ContentResolver的Uri中的id與addURI中的code一至時才返回code
          值不然就返回-1;
          第二種,#號為萬用字元。ContentResolver的Uri中的id不管是什麼值,都會返回addURI中的code值;
         */
    }

得到ContentResolver傳遞過來的引數;(與第6步對應)

操作資料庫;

ContentResolver傳遞Uri地址,以及要操縱資料庫CRUD的對應引數給ContentProvider的CRUD方法;(與第3.4步對應)

//在ContentResolver中uri的ID值有兩種方法
//方法一:
Uri uri = Uri.parse("content://com.example.concentrated/words/6");
//方法二:通過ContentUris的API方法新增id值;
Uri mUri = Uri.parse("content://com.example.concentrated/words");
Uri uri = ContentUris.withAppendedId(mUri, 6);
//ContentUris也可以對uri的id值進行解析;
long wordId = ContenUris.parseId(uri);//獲得結果為6;