UriMatcher和ContentUris简介


我们很经常需要解析Uri,并从Uri中获取数据。

Android系统提供了两个用于操作Uri的工具类,分别为UriMatcher 和ContentUris


UriMatcher 类主要用于匹配Uri.
首先第一步,初始化:
UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);  
 
 
第二步,注册需要的uri:
matcher.addURI("com.yfz.Lesson", "people", PEOPLE);  
matcher.addURI("com.yfz.Lesson", "person/#", PEOPLE_ID);  
第三步,与已经注册的Uri进行匹配:
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".

总结: 

--常量 UriMatcher.NO_MATCH 表示不匹配任何路径的返回码

--# 号为通配符

--* 号为任意字符


3.ContentUris

ContentUris 类用于获取Uri路径后面的ID部分

1)为路径加上ID: withAppendedId(uri, id)

比如有这样一个Uri

Uri uri = Uri.parse("content://com.yfz.Lesson/people")  
通过withAppendedId方法,为该Uri加上ID
Uri resultUri = ContentUris.withAppendedId(uri, 10);  
2)从路径中获取ID: parseId(uri)
Uri uri = Uri.parse("content://com.yfz.Lesson/people/10")  
long personid = ContentUris.parseId(uri);  

转自:http://blog.csdn.net/feng88724/article/details/6331396

猜你喜欢

转载自blog.csdn.net/mahuicool/article/details/78734565