- 简介
- ContentResolver的使用
- 查询、增加、修改、删除
- 应用:介绍上一篇获取通讯录部分的代码
- 自定义内容提供器
ContentProvider可以让不同应用程序之间进行数据共享,它还可以选择只对哪一部分数据进行共享,从而保证程序中的隐私数据不会有泄漏风险。所以组件ContentProvider主要负责存储和共享数据。
ContentProvider有两种形式:可以使用现有的内容提供者来读取和操作相应程序中的数据,也可以创建自己的内容提供者给这个程序的数据提供外部访问接口。(ContentProvider有对外共享数据的功能,换句话说,其他应用程序可以通过ContentProvider对应用中的数据进行增删改查SQLite数据存储的时候就提到过可以实现增删改查的各种辅助性方法,实际上ContentProvider是对SQLiteOpenHelper的进一步封装,因此它们使用的方法太像了,只不过不再用单纯的表名指明被操作的表,毕竟现在是其他程序访问它,而是用有一定格式规范的内容URI来代替。)
ContentResolver的基本用法,方法需要Uri参数,所以先介绍一下URI的组成。
content://com.example.app.provider/table
URI 可以非常清楚地表达出我们想要访问哪个程序中哪张表里的数据,但还没完,还需要将它解析成 Uri 对象才可以作为参数传入。通过调用 Uri.parse()方法,就可以将内容 URI 字符串解析成 Uri 对象了,代码如下:
Uri rui=Uri.parse("content://com.example.app.provider/table")
然后就可以使用这个Uri对象来查询table表的数据了
Cursor cursor=getContentResolver().query(
uri,
projection,
selection,
selectionArgs,
sortOrder);
方法参数 | 对应sql | 描述 |
uri | from table_name | 某个应用程序下的一张表 |
projection | select column1 | 查询指定的列名 |
selection | where column =value | 指定where的约束条件 |
selectionArgs | 为where中的占位符提供具体的值 | |
sortOrder | order by column1 | 指定查询结果的排序方式 |
查询完后返回cursor对象,我们可以将数据从cursor对象中读取出来。
if (cursor != null) {
while (cursor.moveToNext()) {
// 获取联系人姓名
String displayName = cursor.getString(cursor.getColumnIndex("column1"));
// 获取联系人手机号
String number = cursor.getString(cursor.getColumnIndex("column2"));
}
}
查询数据后,接下来进行增加
ContentValues values = new ContentValues();
values.put("column1", 1);
values.put("column2", 2);
getContentResolver().insert(Uri, values); // 插入第一条数据
更新:
ContentValues values = new ContentValues();
values.put("column1", 11);
getContentResolver().update(Uri, values, "column1= ?", new String[] { "6" });
删除:
getContentResolver().delete("Uri", "column = ?", new String[] { "500" });
上一篇文章介绍的是获取通讯录
介绍其中readContacts方法
- getContentResolver().query()来查询系统的联系人数据
- ContactsContract.CommonDataKinds.Phone.CONTENT_URI对应的就是uri,其他的参数都传null
- 接着对cursor进行遍历,取出数据,添加到listview
- 最终将cursor关闭
private void readContacts() {
Cursor cursor = null;
try {
// 查询联系人数据
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
// 获取联系人姓名
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
// 获取联系人手机号
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsList.add(displayName + "\n" + number);
}
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
内容提供器及自定义内容提供器,这里有篇很好的文章访问自定义内容提供器,大佬的文章写的就是好,自己要向大佬学习。。。