android之uriMathcer详解及应用

android之uriMathcer详解及使用

UriMatcher是一个工具类,主要是用于contentProvider中用于匹配URIS。


UriMatcher实际上相当于一棵树,实例化的UriMatcher对象,相当于树的根节点。


UriMatcher的实例化,

UriMatcher  matcher=new UriMatcher(UriMatcher.NO_MACTHER);

UriMatcher.NO_MACTHER是一个常量,如果不匹配就返回-1.


void addURI(String authority, String path, int code)
addURI是添加一个uri,如果这个URi匹配则返回匹配码,不匹配则返回-1.

int match(Uri uri)
从以创建的uri树中去匹配传进来的uri,如果匹配成功,则返回匹配码,否则-1.


下面通过代码去创建一棵树(只有两个节点,文档上的比较多)

public static final int PERSON = 1;//状态码
public static final int NUMBER = 2;

matcher = new UriMatcher(UriMatcher.NO_MATCH);
matcher.addURI("com.example.sqlite", "person", PERSON);
matcher.addURI("com.example.sqlite", "person/#", NUMBER);//#代表任意数字


匹配uri


int code = matcher.match(uri);


SQLiteDatabase data=db.getWritableDatabase();
switch (code) {
case PERSON:


data.delete("person",selection,selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
break;


case NUMBER:


int id=(int) ContentUris.parseId(uri);
selection=(selection==null)?"id="+id:selection+"and id="+id;
data.delete("person", selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
break;


default:
break;
}