UriMatcher和ContentUris简介

来源:互联网 发布:房卡斗地主源码 编辑:程序博客网 时间:2024/05/25 16:38


我们很经常需要解析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


阅读全文
0 0
原创粉丝点击