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) |
int | match(Uri uri) |
下面通過代碼去創建一棵樹(只有兩個節點,文檔上的比較多)
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;
}