Android UriMatcher ContentUris

标签:

android

urimatcher

contenturis

分类: Java

因为Uri代表了要操作的数据,所以我们很经常需要解析Uri,并从Uri中获取数据。Android系统提供了两个用于操作Uri的工具类,分别为UriMatcher 和ContentUris 。掌握它们的使用,会便于我们的开发工作。

UriMatcher

UriMatcher类用于匹配Uri,它的用法如下:

首先第一步,初始化:

 
  1. UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);  

 第二步注册需要的Uri:

 
  1. matcher.addURI("com.yfz.Lesson""people", PEOPLE);  
  2. matcher.addURI("com.yfz.Lesson""person/#", PEOPLE_ID);  

 第三部,与已经注册的Uri进行匹配:

 
  1. Uri uri = Uri.parse("content://" + "com.yfz.Lesson" + "/people");  
  2. int match = matcher.match(uri);  
  3. switch (match)  
  4. {  
  5.     case PEOPLE:  
  6.         return "vnd.android.cursor.dir/people";  
  7.     case PEOPLE_ID:  
  8.         return "vnd.android.cursor.item/people";  
  9.    default:  
  10.         return null;  
  11. }  

match方法匹配后会返回一个匹配码Code,即在使用注册方法addURI时传入的第三个参数。

上述方法会返回"vnd.android.cursor.dir/person".

总结: 

--addURI方法的第二个参数开始时不需要"/", 否则是无法匹配成功的

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

--# 号为通配符

--* 号为任意字符

ContentUris

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

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

 
  1. Uri uri = Uri.parse("content://com.yfz.Lesson/people")  

通过withAppendedId方法,为该Uri加上ID

 
  1. Uri resultUri = ContentUris.withAppendedId(uri, 10);  

最后resultUri为: content://com.yfz.Lesson/people/10

(2)从路径中获取ID: parseId(uri)

 
  1. Uri uri = Uri.parse("content://com.yfz.Lesson/people/10")  
  2. long personid = ContentUris.parseId(uri);  
 
原文地址:https://www.cnblogs.com/jita/p/2243010.html