Content Providers
Content Providers 作用是使得各个应用程序之间实现数据共享。
ContentResolver
ContentResolver cr = getContentResolver();
URI
每个Content Providers都会对外提供一个公共的URI(包装成Uri对象),其他应用程序就可以通过Content Providers传入这个URI来对数据进行操作。
URI由3个部分组成:"content://",数据的路径,标识ID(可选)
系统的一些URI: content://media/internal/images(返回设备上存储的所有图片) content://contacts/people/5(联系人信息中ID为5的联系人记录) content://contacts/people/(返回设备上的所有联系人信息)
系统提供一些辅助类,以类变量形式给出的查询字符串 content://contacts/people/5 ->
Uri person = ContentUris.withAppendedId(People.CONTENT_URI,5);
查询数据
使用ContentResolver.query()或者Activity.managedQuery()传入一个URI来确定当前要操作的数据 返回一个Cursor对象。
//查询联系人信息中ID为5的联系人记录
Uri person = ContentUris.withAppendedId(People.CONTENT_URI,5);
Cursor cur = managedQuery(person,null,null,null);
//取得联系人姓名,电话,并按名字的升序排列
//每个Provider都有一个_id列,为每个记录保存一个数字ID值,
//_COUNT返回记录数,对所有行都是相同的。
String[] projection = new String[]{
People._ID,
People._COUNT,
People.NAME,
People.NUMBER
};
Uri contacts = People.CONTENT_URI;
Cursor managedCursor = managedQuery(
projection,//返回指定列的数据
null, //返回所有行的数据
null, //可选参数
People.NAME+"ASC");//按名字的升序排列
修改数据
private void updateRecord(int id,int num){
Uri uri = ContentUris.withAppendedId(People.CONTENT_URI,id);
ContentValues values = new ContentValues();
values.put(People.NUMBER,num);
getContentResolver().update(uri,values,null,null);
}
添加数据
//调用ContentResolver.insert()方法来添加一条记录
//参数:记录目标的URI,新记录值的ContentValues(Map)对象,返回一个新记录的URI(包含记录号)
ContentValues values = new ContentValues();
values.put(People.NAME,"Abraham");
values.put(People.STARRED,1);
Uri uri = getContentResolver.insert(People.CONTENT_URI,values);
删除数据
Uri uri = People.CONTENT_URI;
getContentResolver().delete(uri,null,null);
//指定where条件语句删除
getContentResolver().delete(uri,"NAME='ABORT'",null);