UriMatcher 和 ContentUris 的用法

一.UriMatcher

UriMatcher 用来匹配Uri;使用addURI向UriMatcher中注册Uri。然后使用UriMatcher判断一个uri是否存在

1.创建:

UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);  

2.注册Uri

private int student=1;

private int studentId=2;

//向UriMatcher中注册Uri

matcher.addURI("com.example.shujuku", "students", student);  

matcher.addURI("com.example.shujuku", "students/#", studentId);  

第三个参数:匹配返回码

3.把现有的uri与注册的uri进行匹配

Uri uri = Uri.parse("content://" + "com.example.shujuku" + "/strdents");  
//match()方法匹配后会返回一个“匹配码”,这个匹配码
int match = matcher.match(uri); switch (match) { case student: return "vnd.android.cursor.dir/strdents"; case studentId: return "vnd.android.cursor.item/strdents"; default: return null; }

UriMatcher.NO_MATCH 没有匹配的Uri返回码(在实例化UriMatcher 时候传入)

# 号为通配符

* 号为任意字符

二。ContentUris

ContentUris主要获取Uri后面的id。

1.获取Uri路径中的Id

Uri uri = Uri.parse("content://com.example.shujuku/students/18")

long personid = ContentUris.parseId(uri);

2.为Uri路径添加Id

Uri uri = Uri.parse("content://com.example.shujuku/students")  

Uri uri_id= ContentUris.withAppendedId(uri, 18);

主要用到了parseId()和withAppendedId()两个方法。一个是用来获取Uri路径中的Id,一个是为Uri添加Id。

原文地址:https://www.cnblogs.com/ywtk/p/3804531.html