内容提供器的用法一般有两种,一种是使用现有的内容提供器来读取和操作响应程序的数据,另一种是创建自己内容提供器给我们程序的数据提供外部访问接口。
ContentResolver的基本用法
对于一个应用,要访问内容提供器中共享的数据,就一定要借助ContentResolver类,可以通过Context中的getContentResolver()方法获取该类的势力,其中提供一系列方法对数据进行操作,其中insert()用于添加数据,update()用于更新数据,delete()用于删除数据,query()用于更新数据。
不同于SQLiteDatabase,该类中增删改查方法不接受表名参数,而使用uri参数代替,内容URI给内容提供器中的数据建立了唯一标识符,由authority和path组成。authority适用于对不同的应用进行区分的,比如一个程序的包名是com.xxx.app那么该程序的authority可以命名为com.xxx.app.provider。path是对同一个应用中不同的表做区分的eg:com.xxx.app.provider/table1和com.xxx.app.provider/table2
因此内用URI最标准的格式写法如下:content://com.example.app.provider/table1
在得到了内容URI字符串之后,我们还需要将它解析成Uri对象才可以作为参数传入
eg:Uri uri = Uri.parse("content://com.example.app.provider/table1");
只需要调用Uri.parse()方法就可以将URI字符串解析成Uri对象了
我们就可以使用这个Uri对象来查询table1中的数据了
Cursor cursor = getContentResolver().query(
uri,
projection,
selection,
selectionArgs,
sortOrder);
查询完成后返回的仍然是一个Cursor对象,这时我们就可以将数据从Cursor对象中逐个读取出来了。读取的思路是通过移动游标的位置来遍历Cursor的所有行,然后再去出每一个行中相应列的数据,代码如下
if (cursor!=null){
while (cursor.moveToNext()){
String colume1 = cursor.getString(cursor.getColumnIndex("column1"));
int colume2 = cursor.getInt(cursor.getColumnIndex("column2"));
}
cursor.close();
}
增添一条数据
ContentValues values = new ContentValues();
values.put("column1","text");
values.put("column2",1);
getContentResolver().insert(uri,values);
更新数据,借助ContentResolver的update()方法来实现
ContentValues values = new ContentValues();
values.put("column1","");
getContentResolver().update(uri,values,"column1=?andcolumn2=?",new String[]{"text",1});
删除数据
getContentResolver().delete(uri,"column2=?",new String[]{"1"});