ContentProvider 被訪問的(一)

提供數據被訪問的一方。

public class WordProvider extends ContentProvider {

    private UriMatcher matcher;

    private static final int MATCH_ROOT = 1;
    private static final int MATCH_HELLO = 2;

    @Override
    public boolean onCreate() {
        // 當本ContentProvider被創建時回調

        // 第一步,創建UriMatcher對象
        matcher = new UriMatcher(UriMatcher.NO_MATCH);
        // 第二步,添加匹配的URI,並指定匹配時的返回值
        //MATCH_ROOT   MATCH_HELLO  就是返回值
        matcher.addURI("cn.teee.providers.word", null, MATCH_ROOT);
        matcher.addURI("cn.teee.providers.word", "hello", MATCH_HELLO);

        return false;
    }

    // content://cn.teee.providers.word
    // content://cn.teee.providers.word/hello

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        // 當其它應用查詢數據時回調
        //第三步,與已經註冊的URI進行匹配
        switch (matcher.match(uri)) {
        //根據返回值做判斷
        case MATCH_ROOT:
            DBOpenHelper dbOpenHelper = new DBOpenHelper(getContext());
            SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
            Cursor c = db.query("word", projection, selection, selectionArgs, null, null, sortOrder);
            return c;

        default:
            throw new RuntimeException("非法的Uri -> " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // 當其它應用添加數據時回調

        // 驗證Uri
        //第三步,與已經註冊的URI進行匹配
        int code = matcher.match(uri);
        Log.d("teee", "uri -> " + uri.toString());
        switch (code) {
        //根據返回值做判斷
        case MATCH_ROOT:
            Log.d("teee", "MATCH_ROOT");
            DBOpenHelper dbOpenHelper = new DBOpenHelper(getContext());
            SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
            long id = db.insert("word", null, values);
            if (db.isOpen()) {
                db.close();
                db = null;
            }
            // content://cn.teee.providers.word/13
            return ContentUris.withAppendedId(uri, id);

        case MATCH_HELLO:
            Log.d("teee", "MATCH_HELLO");
            throw new RuntimeException("非法的Uri:" + uri);

        case UriMatcher.NO_MATCH:
            Log.d("teee", "NO_MATCH");
            throw new RuntimeException("非法的Uri:" + uri);
        }

        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // 當其它應用刪除數據時回調
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        // 當其它應用修改數據時回調
        // -- 假設不提供修改數據的服務 --
        throw new RuntimeException("不允許修改數據!!!");
    }

    @Override
    public String getType(Uri uri) {
        // (無視)
        return null;
    }

}
發佈了97 篇原創文章 · 獲贊 20 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章