問題聚焦:
思想:應用程式資料的共用
對資料庫的訪問僅限於建立它的應用程式,但是事情不是絕對的
Content Provider提供了一個標準的介面,可供其他應用程式訪問和使用其他程式的資料
下面我們由下向上來分析ContentProvider的處理流程:
1 資料庫——SQLite使用者:ContentProvider映射:Content Value映射為資料庫中的表的一行;查詢:Cursor,底層資料中的結果集的指標;使用:SQLiteOpenHelper,抽象類別,用於實現建立、開啟和升級資料庫
繼承該類,重寫其建構函式,onCreate方法(建立)和onUpgrade方法(更新)
訪問:getWritableDatabase方法(獲得可寫的資料庫執行個體)和getReadableDatabase方法(擷取唯讀資料庫執行個體)
Demo
/** 插入新行 **/// 建立要插入的一行新值ContentValues newValues = new ContentValues();//為每一個欄位賦值newValues.put(NAME_COLUMN, _name);newValues.put(ADDRESS_COLUMN, _address);......//插入到資料庫中SQLiteDatabase db = DBOpenHelper.getWritableDatabase();db.insert(DBOpenHelper.DATABASE_TABLE, null, newValues);
2 Content Provider使用者:自身為獨立的APP作用:將使用資料的應用程式組件和底層的資料來源分離使用:ContentProvider,抽象類別,繼承該類,並重寫方法:
onCreate(): 初始化底層的資料來源query()update()delete()insert()getType()
註冊:通過標記實現,name屬性+authorities標記
demo:
發布:URI demo:
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/item"); public static final Uri CONTENT_POS_URI = Uri.parse("content://" + AUTHORITY + "/pos");使用:應用程式通過ContentResolver與ContentProvider互動
3 ContentResolver——使用ContentProvider使用者:應用程式作用:應用程式通過它來查詢和操作Content Provdier特點:ContentProvider提供了底層資料的抽象
ContentResolver提供了查詢和處理ContentProvider的抽象
使用:通過URI互動Demo
/** 查詢操作 **/ public Article getArticleById(int id) { Uri uri = ContentUris.withAppendedId(Articles.CONTENT_URI, id); String[] projection = new String[] { Articles.ID, Articles.TITLE, Articles.ABSTRACT, Articles.URL }; Cursor cursor = resolver.query(uri, projection, null, null, Articles.DEFAULT_SORT_ORDER); // 擷取一個資料庫的遊標 Log.i(LOG_TAG, "cursor.moveToFirst"); if (!cursor.moveToFirst()) { return null; } String title = cursor.getString(1); String abs = cursor.getString(2); String url = cursor.getString(3); return new Article(id, title, abs, url); }
4 URIUri代表了要操作的資料格式:content:// 主機名稱(或叫Authority)用於唯一標識這個ContentProvider,外部調用者可以根據這個標識來找到它。路徑(path)可以用來表示我們要操作的資料
5 小結:一張圖概括一下這章的內容:
編程3rd》 ContentProvider和Uri詳解: http://www.cnblogs.com/linjiqin/archive/2011/05/28/2061396.html