当外部应用需要对
ContentProvider
中的数据进行添加、删除、修改和查询操作时,可以使用
ContentResolver
类来完成,
要获取
ContentResolver
对象,可以使用
Activity
提供的
getContentResolver()
方法。
ContentResolver
类提供了与
ContentProvider
类相同签名的四个方法:
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
中获取数据。
这些方法的第一个参数为
Uri
,代表要操作的是哪个
ContentProvider
和对其中的什么数据进行操作,假设给定的是:
Uri.parse(“content://cn.itcast.provider.personprovider/person/10”)
,那么将会对主机名为
cn.itcast.provider.personprovider
的
ContentProvider
进行操作,操作的数据为
person
表中
id
为
10
的记录。
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
使用
ContentResolver
对
ContentProvider
中的数据进行添加、删除、修改和查询操作:
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://cn.itcast.provider.personprovider/person");
//
添加一条记录
ContentValues values = new ContentValues();
values.put("name", "itcast");
values.put("age", 25);
resolver.insert(uri, values);
//
获取
person
表中所有记录
Cursor cursor = resolver.query(uri, null, null, null, "personid desc");
while(cursor.moveToNext()){
Log.i("ContentTest", "personid="+ cursor.getInt(0)+ ",name="+ cursor.getString(1));
}
//
把
id
为
1
的记录的
name
字段值更改新为
liming
ContentValues updateValues = new ContentValues();
updateValues.put("name", "liming");
Uri updateIdUri = ContentUris.withAppendedId(uri, 2);
resolver.update(updateIdUri, updateValues, null, null);
//
删除
id
为
2
的记录
Uri deleteIdUri = ContentUris.withAppendedId(uri, 2);
resolver.delete(deleteIdUri, null, null);