ContentProvider是Android四大组件之一,网上也有不少关于它的文章,基本用法都可以查到,但关于UriMatcher在其中的作用,文章中都有例子,但我觉得还没有说清楚。
先说为什么用UriMatcher。
ContentProvider向外界提供了一个标准的,也是唯一的用于查询的接口:
public final Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);
public static final Uri CONTENT_URI_A = Uri.parse("content://" + AUTHORITY + "/" + TABLE_A); public static final Uri CONTENT_URI_B = Uri.parse("content://" + AUTHORITY + "/" + TABLE_B);
再说怎么用UriMatcher, 定义如下:
// Set up our URL matchers to help us determine what an // incoming URI parameter is. private static final UriMatcher URI_MATCHER; static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(AUTHORITY, TABLE_A, TABLE_A_MSG); URI_MATCHER.addURI(AUTHORITY, TABLE_B, TABLE_B_MSG); }
在查询中使用UriMatcher:
@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String table = null; switch (URI_MATCHER.match(uri)) { case ALL_MESSAGES: break; case OXFORD_MSG: table = TABLE_A; break; case CHENYU_MSG: table = TABLE_B; break; default: break; } Cursor resultCursor = mDB.query(table, projection, selection, selectionArgs, null, null, sortOrder); return resultCursor; }