一、內容提供器
使用內容提供器來共享資料 可以精確的進行控制,哪些資料可以共享,哪些資料不可以共享 內容提供器有兩種用法:(1)使用現有的內容提供器來讀取和操作相應程式中的資料;(2)創建自己的內容提供器給我們的程式的資料提供外部訪問介面
二、ContentResolver的基本用法
獲取ContentResolver實體的方法: new Context().getContentResolver() 該實體提供了一系列方法insert(),update(),delete(),query()用于CRUD操作 這些成員方法在引數上與SQLiteDatabase實體有一些不同 表名引數變成了Uri引數(內容URI) URI有連部分組成:權限和路徑 權限用于不同的程式來進行區分的,都采用程式包命名的方式,比如某個程式包為 com.example.app那么該程式對應的權限可以命名為com.example.app.provide路徑則是用于對同一個應用程式中的不同的表進行區分的,通常會添加到權限后面,比如一個程式中含有兩個表table1和table2,那么可以將路徑分別命名為/table1和/table2,然后進行二者組合,內容Url變成了 com.example.app.provider/table1和com.example.app.provider/table2還需要在頭部加上協議 content://com.example.app.provider/table1對于這個字串我們需要決議為Uri物件才能作為引數傳入
Uri uri = Uri.parse("content://com.example.app.provider/table1");
查詢代碼如下
Cursor cursor = getContentResolver().query(uri,projection,selection,selectionArgs,sortOrder);
這些引數我們做一個對比就一目了然了
| query()方法引數 | 對應SQL部分 | 描述 |
|---|---|---|
| uri | from table_name | 指定查詢某個應用程式下的某一張表 |
| projection | select colum1,column2 | 指定查詢的列名 |
| selection | where column = value | 指定where的約束條件 |
| selectionArgs | 為where中的占位符提供具體的值 | |
| orderBy | order by column1,column2 | 指定查詢結果的排序方式 |
查詢后回傳一個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();
}
剩下的增刪該就不難了
ContentValues values = new ContentValues();
values.put("column1","text");
values.put("column2","text");
getContentResolver().insert(uri,values);
上面時插入資料,下面來一個更新資料
ContentValues values = new ContentValues();
values.put("column1","");
getContentResolver().update(uri,values,"column1 = ? and column2 = ?",new String[] {"text","1"});
洗掉資料
getContentResolver().delete(uri,"column2 = ?",new String[]{"1"});
三、原始碼:
CSDN:https://blog.csdn.net/weixin_44630050 博客園:https://www.cnblogs.com/ruigege0000/ 歡迎關注微信公眾號:傅里葉變換,個人賬號,僅用于技術交流
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/163909.html
標籤:其他
