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;
}



發佈了42 篇原創文章 · 獲贊 26 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章