学习ContentProvider 和ContentResolver时:
两个用于操作Uri的工具类,分别为UriMatcher 和ContentUris。
UriMatcher 用于匹配Uri。
用法如下:
首先把你需要匹配Uri路径全部给注册上:
//UriMatcher : 用于匹配Uri的容器
private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
//添加一个uri
//*:代表任何text, #:代表任何number, other:代表精确匹配
uriMatcher.addURI(AUTHORITY, "person ", 1);
uriMatcher.addURI(AUTHORITY, "person /#", 2);
}
注 册完需要匹配的Uri后,就可以使用uriMatcher.match(uri)方法对输入的Uri进行匹配,
如果匹配就返回匹配码,匹配码是调用 addURI()方法传入的第三个参数,
例如匹配content://com.test.provider.personprovider/person 路径,返回的匹配码为1。
//常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码
UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
添加需要匹配的uri,如果匹配就会返回匹配码如果match()方法匹配content://com.test.provider.personprovider/person路径,返回匹配码为1 uriMatcher.addURI(“com.test.provider.personprovider”, “person”, 1);
如果match()方法匹配content://com.test.provider.personprovider/person/530路径,返回匹配码为2
//#号为通配符
uriMatcher.addURI(“com.test.provider.personprovider”, “person/#”, 2);
ContentUris类
用于获取Uri路径后面的ID部分:
1、ContentUris.withAppendedId(Uri contentUri, long id)用于为路径加上ID部分:
Uri uri = Uri.parse("content://com.test.provider.personprovider/person")
Uri resultUri = ContentUris.withAppendedId(uri, 5);
生成后的Uri为:content://com.test.provider.personprovider/person/5其结果等价于Uri.withAppendedPath(Uri baseUri, String pathSegment)
Uri resultUri = Uri.withAppendedPath(uri, "5");
2、ContentUris.parseId(uri)方法用于从路径中获取ID部分:
Uri uri = Uri.parse("content://com.test.provider.personprovider/person/5")
long personid = ContentUris.parseId(uri); //获取的结果为:5
ContentResolver :
通过URI来添加、删除、修改和查询ContentProvider中提供的数据。除了URI以外,还必须知道需要获取的数据段的名称,以及此数据段的数据类型。如果你需要获取一个特定的记录,你就必须知道当前记录的ID,也就是URI中D部分。 可以使用Activity提供的getContentResolver()方法。
ContentResolver使用insert、delete、update、query方法来操作数据。