涉及項目代碼地址:
https://download.csdn.net/download/jifenglie/12040917
https://download.csdn.net/download/jifenglie/12040923
ContentResolver的基本用法
對於每一個應用程序來說,如果想要訪問內容提供器中共享的數據,就一定要藉助Content- Resolver 類,可以通過 Context 中的 getContentResolver() 方法獲取到該類的實例。 Content- Resolver中提供了一系列的方法用於對數據進行CRUD操作,其中insert()方法用於添加數據, update()方法用於更新數據,delete()方法用於刪除數據,query()方法用於查詢數據。有沒 有似曾相識的感覺?沒錯,SQLiteDatabase中也是使用這幾個方法來進行CRUD操作的,只不過 它們在方法參數上稍微有一些區別。
不同於SQLiteDatabase,ContentResolver中的增刪改查方法都是不接收表名參數的,而是使 用一個Uri參數代替,這個參數被稱爲內容URI。內容URI給內容提供器中的數據建立了唯一 標識符,它主要由兩部分組成:authority和path。authority是用於對不同的應用程序做區分的, 一般爲了避免衝突,都會採用程序包名的方式來進行命名。比如某個程序的包名是com.example. app,那麼該程序對應的authority就可以命名爲com.example.app. provider。path則是用於對同一 應用程序中不同的表做區分的,通常都會添加到authority的後面。比如某個程序的數據庫裏存在 兩張表:tablel和table2,這時就可以將path分別命名爲/tablel和/table2,然後把authority和path 進行組合,內容 URI 就變成了 com.example.app.provider/tablel 和 com.example.app.provider/table2。
不過,目前還很難辨認出這兩個字符串就是兩個內容URI,我們還需要在字符串的頭部加上協議
聲明。因此,內容URI最標準的格式寫法如下:
content://com.example.app.provider/tablel1
content://com.example.app.provider/table2
有沒有發現,內容URI可以非常清楚地表達出我們想要訪問哪個程序中哪張表裏的數據。 也正是因此,ContentResolver中的增刪改查方法才都接收Uri對象作爲參數,因爲如果使用表名 的話,系統將無法得知我們期望訪問的是哪個應用程序裏的表。
在得到了內容URI字符串之後,我們還需要將它解析成Uri對象方可以作爲參數傳人。解 析的方法也相當簡單,代碼如下所示:
Uri uri = Uri.parse("content://com.example.app.provider/table1")
只需要調用Uri.parse方法,就可以將內容URI字符串解析成Uri對象了。
現在我們就可以使用這個Uri對象來查詢tablet表中的數據了,代碼如下所示:
Cursor cursor = getContentResolver().query(
uri,
projection,
selection,
selectionArgs,
sortOrder);
這些參數和SQLiteDatabase中query()方法裏的參數很像,但總體來說要簡單一些,畢竟這是在訪問其他程序中的數據,沒必要構建過於複雜的查詢語句。下表對使用到的這部分參數進行了詳細的解釋。
查詢完成後返間的仍然是一個Cursor對象,這時我們就可以將數據從Cursor對象中逐個讀取出來了。讀取的思路仍然是通過移動遊標的位置來遍歷Cursor的所有行,然後再取出每一行中相應列的數據,代碼如下所示:
if (cursor != null) {
while (cursor.moveToNext()) {
String column1 = cursor.getString(cursor.getColumnIndex{"column1"));
int column2 = cursor.getInt(cursor.getColumnIndex("column2"));
}
cursor.close();
}
掌握了最難的查詢操作,剩下的增加、修改、刪除操作就更不在話下了。我們先來看看如何向table1表中添加一條數據,代碼如下所示:
ContentValues values = new ContentValues();
values.put("column1", ''text");
values.put("column2", 1);
getContentResolver().insert(uri, values);
可以看到,仍然是將待添加的數據組裝到ContentValues中,然後調用ContentResolver的insert ()方法,將Uri和ContentValues作爲參數傳人即可。
現在如果我們想要更新這條新添加的數據,把column1的值清空,可以藉助ContentResolver的update()方法實現,代碼如下所示:
ContentValues values = new ContentValues();
values.put("column1","");
getContentResolver(),update(uri, values, "column1 = ? and column2 = ?",new String[] {"text","1"});
注意上述代碼使用了 selection和selectionArgs參數來對想要更新的數據進行約束,以防止所有的行都會受影響。
最後,可以調用ContentResolver的delete()方法將這條數據刪除掉,代碼如下所示:
getContentResolver().delete(uri, "column2 = ?", new String[] { "1" });
到這爲止,我們就把ContentResolver中的增刪改查方法全部學完了。
創建自己的內容提供器(實現跨程序數據共享)
新建DatabaseTest項目
創建MyDatabaseHelper 繼承SQLiteOpenHelper
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK = "create table Book("
+ "id integer primary key autoincrement,"
+ "author text,"
+ "price real,"
+ "pages integer,"
+ "name text)";
private Context mContext;
public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
創建DatabaseProvider 繼承ContentProvider
public class DatabaseProvider extends ContentProvider {
public static final int BOOK_DIR = 0;
public static final int BOOK_ITEM = 1;
public static final int CATEGORY_DIR = 2;
public static final int CATEGORY_ITEM = 3;
public static final String AUTHORITY = "com.zjsos.www.databasetest.provider";
private static UriMatcher uriMatcher;
private MyDatabaseHelper dbHepler;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, "book", BOOK_DIR);
uriMatcher.addURI(AUTHORITY, "book/#", BOOK_ITEM);
uriMatcher.addURI(AUTHORITY, "category", CATEGORY_DIR);
uriMatcher.addURI(AUTHORITY, "category/#", CATEGORY_ITEM);
}
@Override
public boolean onCreate() {
dbHepler = new MyDatabaseHelper(getContext(), "BookStore.db", null, 2);
return true;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
SQLiteDatabase db = dbHepler.getWritableDatabase();
Cursor cursor = null;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
cursor = db.query("Book", projection, selection, selectionArgs, null, null, sortOrder);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
cursor = db.query("Book", projection, "id=?", new String[]{bookId}, null, null, sortOrder);
break;
case CATEGORY_DIR:
cursor = db.query("Category", projection, selection, selectionArgs, null, null, sortOrder);
break;
case CATEGORY_ITEM:
String categoryId = uri.getPathSegments().get(1);
cursor = db.query("Category", projection, "id=?", new String[]{categoryId}, null, null, sortOrder);
break;
default:
break;
}
return cursor;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
SQLiteDatabase db = dbHepler.getWritableDatabase();
Uri uriReturn = null;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
case BOOK_ITEM:
long newBookId = db.insert("Book", null, values);
uriReturn = Uri.parse("content://" + AUTHORITY + "/book/" + newBookId);
break;
case CATEGORY_DIR:
case CATEGORY_ITEM:
long newCategoryId = db.insert("Category", null, values);
uriReturn = Uri.parse("content://" + AUTHORITY + "/category/" + newCategoryId);
break;
default:
break;
}
return uriReturn;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
//更 新 教 據
SQLiteDatabase db = dbHepler.getWritableDatabase();
int updatedRows = 0;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
updatedRows = db.update("Book", values, selection, selectionArgs);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
updatedRows = db.update("Book", values, "id = ?", new String[]{bookId});
break;
case CATEGORY_DIR:
updatedRows = db.update("Category", values, selection, selectionArgs);
break;
case CATEGORY_ITEM:
String categoryId = uri.getPathSegments().get(1);
updatedRows = db.update("Category", values, "id = ?", new String[]{categoryId});
break;
default:
break;
}
return updatedRows;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[]
selectionArgs) {
//刪除數據
SQLiteDatabase db = dbHepler.getWritableDatabase();
int deletedRow = 0;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
deletedRow = db.delete("Book", selection, selectionArgs);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
deletedRow = db.delete("Book", "id =?", new String[]{bookId});
break;
case CATEGORY_DIR:
deletedRow = db.delete("Category", selection, selectionArgs);
break;
case CATEGORY_ITEM:
String categoryId = uri.getPathSegments().get(1);
deletedRow = db.delete("Category", "id =?", new String[]{categoryId});
break;
default:
break;
}
return deletedRow;
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
return "vnd.android.cursor.dir/vnd.com.example.databasetest.provider.book";
case BOOK_ITEM:
return "vnd.android.cursor.item/vnd.com.example.databasetest.provider.book";
case CATEGORY_DIR:
return "vnd.android.cursor.dir/vnd.com.example.databasetest.provider.category";
case CATEGORY_ITEM:
return "vnd.android.cursor.item/vnd.com.example.databasetest.provider.category";
}
return null;
}
}
getType ( )說明
根據傳入的內容 URI 來返回相應的 MIME 類型。
可以看到,兒乎每一個方法都會帶有 uri 這個參數,這個參數也正是調用 ContentResolver 的增刪改查方法時傳遞過來的。而現在,我們需要對傳人的 Uri 參數進行解析,從中分析出調用方期望訪問的表和數據。
回顧一下,一個標準的內容 URI 寫法是這樣的:
content://com.example.app.provider/table1
這就表示調用方期望訪問的是 com . example . app 這個應用的 tablel1表中的數據。除此之外,我們還可以在這個內容 URI的後面加上一個id,如下所示:
content://com.example.app.provider/table/1
這就表示調用方期望訪問的是 com.example.app 這個應用的 table 表中 id 爲 1 的數據。
內容 URI 的格式主要就只有以上兩種,以路徑結尾就表示期望訪問該表中所有的數據,以 id 結尾就表示期望訪問該表中擁有相應 id 的數據。我們可以使用通配符的方式來分別匹配這兩種格式的內容URI,規則如下。
* 表示匹配任意長度的任意字符。
# 表示匹配任意長度的數字。
所以,一個能夠匹配任意表的內容URI格式就可以寫成:
content://com.example.app.provider/*
而一個能夠匹配tablel表中任意一行數據的內容URI格式就可以寫成:
content://com.example.app.provider/tablel/#
接着,我們藉助UriMatcher這個類就可以輕鬆地實現匹配內容URI的功能。UriMatcher中提供了一個addUR()方法,這個方法接收3個參數,可以分別把authority、path和一個自定義代碼傳進去。這樣,當調用UriMatcher的match()方法時,就可以將一個Uri對象傳入,返回值是某個能夠匹配這個Uri對象所對應的自定義代碼,利用這個代碼,我們就可以判斷出調用方期望訪問的是哪張表中的數據了。
配置Provider
<provider
android:name=".DatabaseProvider"
android:authorities="com.zjsos.www.databasetest.provider"
android:enabled="true"
android:exported="true" />
添加數據讀寫權限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
新建ProviderTest項目
通過新建項目去訪問DatabaseTest項目中數據
編寫activity_main.xml佈局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/add_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add To Book" />
<Button
android:id="@+id/query_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Qurey From Book" />
<Button
android:id="@+id/update_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Update Data" />
<Button
android:id="@+id/delete_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Delete Data" />
</LinearLayout>
編寫主頁面MainActivity代碼
public class MainActivity extends AppCompatActivity {
private String newId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addData = (Button) findViewById(R.id.add_data);
addData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("content://com.zjsos.www.databasetest.provider/book");
ContentValues values = new ContentValues();
values.put("name", "A Clash of Kings");
values.put("author", "George Martin");
values.put("pages", 1040);
values.put("price", 22.85);
Uri newUri = getContentResolver().insert(uri, values);
newId = newUri.getPathSegments().get(1);
}
});
Button queryData = (Button) findViewById(R.id.query_data);
queryData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("content://com.zjsos.www.databasetest.provider/book");
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
String author = cursor.getString(cursor.getColumnIndex("author"));
int pages = cursor.getInt(cursor.getColumnIndex("pages"));
double price = cursor.getDouble(cursor.getColumnIndex("price"));
Log.e("MainActivity", "book name is" + name);
Log.e("MainActivity", "book author is" + author);
Log.e("MainActivity", "book pages is" + pages);
Log.e("MainActivity", "book price is" + price);
if (Integer.parseInt(Build.VERSION.SDK) < 14) {
//只有4.0以下才需要手動關閉
cursor.close();
}
}
}
}
});
Button updateData = (Button) findViewById(R.id.update_data);
updateData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("content://com.zjsos.www.databasetest.provider/book/" + newId);
ContentValues values = new ContentValues();
values.put("name", " A Storm of Swords");
values.put("pages", 1216);
values.put("price", 24.85);
getContentResolver().update(uri, values, null, null);
}
});
Button deleteData = (Button) findViewById(R.id.delete_data);
deleteData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("content://com.zjsos.www.databasetest.provider/book/" + newId);
getContentResolver().delete(uri, null, null);
}
});
}
}
運行安裝DatabaseTest項目,打開項目,然後運行安裝ProviderTest項目
點擊ProviderTest項目中ADD TO BOOK按鈕,此時數據應該已經添加到DatabaseTest項目,點擊QUREY FROM BOOK按鈕查看打印日誌就可以查看到數據了
點擊upadte data修改按鈕,在點擊query from book查詢,查看數據庫已經改變
點擊delete data按鈕,在點擊query from book按鈕,就查詢不到數據了,測試完成
參考:第一行代碼Android 第2版 郭霖 著 建議大家去買下正版書 支持下郭老師