访问其他程序中的数据:
内容提供器的用法一般有两种:
1.使用现有的内容提供器来读取和操作相应程序中的数据。
2。创建自己的内容提供器给我们程序的数据提供外部访问接口。
ContentResolver的基本用法
要想访问内容提供器中共享的数据:就一定要借助ContentResolver类。
可以通过Context中的getContentResolver()方法获取到该类的实例。
ContentResolver中提供了一系列的方法用于对数据进行CRUD操作。
public Uri insert(Uri uri, ContentValues values)
//该方法用于往ContentProvider添加数据。
public int delete(Uri uri, String selection, String[] selectionArgs)
//该方法用于从ContentProvider删除数据。
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
//该方法用于更新ContentProvider中的数据。
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
//该方法用于从ContentProvider中获取数据。
可能发现了,ContentResolver中的增删改查方法都是不接收表名参数的,而是使用一个Uri参数代替,这个参数被称为内容URI。内容URI给内容提供器中的数据建立了唯一标识符,它主要由两部分组成:
1:authority:用于对不同的应用程序做区分的,一般为了避免冲突,都会采用程序包名的方式来进行命名。
2:path:用于对同一应用程序中不同的表做区分的,通常都会添加到authority的后面。
3:最后我们还需要在字符串的头部加上协议声明。
例如:
content://com.example.app.provider/table1
content://com.example.app.provider/table2
在得到了内容URI字符串之后,我们还需要将它解析成Uri对象才可以作为参数传入。代码如下:
Uri uri = Uri.parse("content://com.example.app.provider/table1");
只需要调用Uri.parse()方法,就可以将内容URI字符串解析成Uri对象。
查询table1表中的数据
Cursor cursor = getContentResolver().query(
uri,//指定查询某个应用程序下的某一张表
projection,//指定查询的列名
selection,//指定where的约束条件
selectionArgs,//为where中的占位符提供具体的值
sortOrder);//指定查询结果的排序方式
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","1");
getContentResolver().insert(uri,values);
可以看到,仍然是将待添加的数据组装到ContentValues中,然后调用ContentResolver的insert()方法,将Uri和ContentValues作为参数传入即可。
更新一条数据
ContentValues values= new ContentValues();
values.put("column1","");
getContentResolver().update(uri,values,"column1 = ? and column2 = ?",new String []{
"text","1"});
注意上述代码使用了selection和selectionArgs参数来对想要更新的数据进行约束,以防止所有的行都会受影响。
删除一条数据
getContentResolver().delete(uri,"column2 = ?",new String[]{
"1"});