一、内容提供器
- 可以精确的进行控制,哪些数据可以共享,哪些数据不可以共享
- 内容提供器有两种用法:(1)使用现有的内容提供器来读取和操作相应程序中的数据;(2)创建自己的内容提供器给我们的程序的数据提供外部访问接口
二、ContentResolver的基本用法
- 获取ContentResolver实例的方法: new Context().getContentResolver()
- 该实例提供了一系列方法insert(),update(),delete(),query()用于CRUD操作
- 这些成员方法在参数上与SQLiteDatabase实例有一些不同
- 权限用于不同的程序来进行区分的,都采用程序包命名的方式,比如某个程序包为
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"});
三、源码:
- 欢迎关注微信公众号:傅里叶变换,个人账号,仅用于技术交流
![20.5](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9zdGF0aWMwMS5pbWdrci5jb20vdGVtcC9iZDdjNjY1NjM4YWY0ODBlOTdmMThhZmQ1MDYyYTQxNi5qcGc?x-oss-process=image/format,png)