Content Provider介绍
- 内容提供器主要用于在不同应用之间实现数据共享的功能,它提供了一套完整的机制,允许一个程序访问另一个程序中的数据,同时还能保证被访问数据的安全性。目前,使用内容提供器是android实现跨程序共享数据的标准方式。
ContentResolver的基本用法
- ContentResolver的用法和SQLiteBase非常相似,都是具有增删改查的方法,只不过ContentResolver中的增删改查的方法不接收表名,而是使用一个Uri参数代替,称为内容URI
- 内容URI是给内容提供器中的数据建立的唯一标识符,它主要有两部分组成,权限和路径
- 权限一般采用包名做唯一标识:若某一个程序的包名为com.example.app,那么其权限就是com.example.app.provider
- 路径则是对同一数据库中的表进行区分的:若存在两张表table1和table2,分别命名/table1和/table2
内容URI标准格式
content://com.example.app.provider/table1
content://com.example.app.provider/table2
- 只需要调用Uri uri=Uri.parse(“content://com.example.app.provider/table2”);就可以得到内容URI了
- 内容URI中可以加入通配符*或#
content://com.example.app.provider
content://com.example.app.provider/table1/#
- 表示一个能够匹配table1表中任意一行数据的内容URI
增删改查
查询语句
Cursor cursor=getContentResolver().query(uri,projection,selection,selectionArgs,sortOrder);
- 第一个参数指定查询某个应用程序的某一张表
- 第二个参数指定查询的列名
- 第三个参数指定where约束条件
- 第四个参数为where中的占位符指定具体的值
- 第五个参数指定查询结果的排序方式
- 查询完成后返回一个Cursor对象,通过对其的遍历,就可以获取到所有的查询结果。
增加语句
ContentValues values=new ContentValues();
values.put("column1","text");
values.put("column2",1);
getContentResolver().insert(uri,values);
修改语句
ContentValues values=new ContentValues();
values.put("column1","hello");
values.put("column2",15);
getContentResolver().update(uri,values,"column1=? and column2=?",new String[]{"text","1"});
删除语句
getContentResolver().delete(uri,"column1=?",new String[]{"hello"});