因为Uri代表了要操作的数据,所以我们很经常需要解析Uri,并从Uri中获取数据。Android系统提供了两个用于操作Uri的工具类,分别为UriMatcher 和ContentUris 。掌握它们的使用,会便于我们的开发工作。
UriMatcher
UriMatcher类用于匹配Uri,它的用法如下:
首先第一步,初始化:
- UriMatcher
matcher = new UriMatcher(UriMatcher.NO_MATCH);
- matcher.addURI("com.yfz.Lesson",
"people", PEOPLE); - matcher.addURI("com.yfz.Lesson",
"person/#", PEOPLE_ID);
- Uri
uri = Uri.parse("content://" + "com.yfz.Lesson" + "/people"); - int
match = matcher.match(uri); - switch
(match) - {
-
case PEOPLE: -
return "vnd.android.cursor.dir/people"; -
case PEOPLE_ID: -
return "vnd.android.cursor.item/people"; -
default: -
return null; - }
match方法匹配后会返回一个匹配码Code,即在使用注册方法addURI时传入的第三个参数。
上述方法会返回"vnd.android.cursor.dir/person".
总结:
--addURI方法的第二个参数开始时不需要"/", 否则是无法匹配成功的。
--常量 UriMatcher.NO_MATCH 表示不匹配任何路径的返回码
--# 号为通配符
--* 号为任意字符
ContentUris
ContentUris 类用于获取Uri路径后面的ID部分
(1)为路径加上ID: withAppendedId(uri, id)
- Uri
uri = Uri.parse("content://com.yfz.Lesson/people")
通过withAppendedId方法,为该Uri加上ID
- Uri
resultUri = ContentUris.withAppendedId(uri, 10);
最后resultUri为: content://com.yfz.Lesson/people/10
(2)从路径中获取ID: parseId(uri)
- Uri
uri = Uri.parse("content://com.yfz.Lesson/people/10") - long
personid = ContentUris.parseId(uri);
最后personid 为 :10