UriMatcher没有认识到模式

时间:2013-06-02 03:38:33

标签: android uri android-contentprovider

我在ContentProvider中匹配URI时遇到问题。它会将路径与一个或两个“标记”匹配(不确定正确的术语是什么),例如它可以识别box/#。但是,只要我添加第二个标记,例如box/#/item,我就会抛出InvalidArgumentException并且我的应用程序崩溃了。我在这里阅读了几个主题,这个问题有时可以通过改变添加到UriMatcher的URI的顺序来解决;我试过这个,但无济于事。谁知道问题是什么?我已经摘录了下面代码的相关部分。

来自我的ContentProvider

private static final String AUTHORITY = "com.example.boxdatabase.DatabaseProvider";
// Type of query
public static final int BOXES = 100;
    ...

public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
    ...

// URI Matcher for queries
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
    sURIMatcher.addURI(AUTHORITY, "box/#/item", BOX_ITEM);
    sURIMatcher.addURI(AUTHORITY, "box/#/item/#", BOX_ITEM_ID);
    sURIMatcher.addURI(AUTHORITY, "box", BOXES);
    sURIMatcher.addURI(AUTHORITY, "box/#", BOXES_ID);
    sURIMatcher.addURI(AUTHORITY, "item", ITEMS);
    sURIMatcher.addURI(AUTHORITY, "item/#", ITEMS_ID);
}

我尝试访问ContentProvider并尝试访问失败的示例:

return new CursorLoader(this, Uri.withAppendedPath(
                DatabaseProvider.CONTENT_URI, "box/" + boxId + "/item"),
                DatabaseContract.BoxItemEntry.ALL_COLUMNS, null, null, null);

1 个答案:

答案 0 :(得分:4)

试试这个:

sURIMatcher.addURI(AUTHORITY, "box", BOXES);
sURIMatcher.addURI(AUTHORITY, "box/#", BOXES_ID);
sURIMatcher.addURI(AUTHORITY, "box/#/item", BOX_ITEM);
sURIMatcher.addURI(AUTHORITY, "box/#/item/#", BOX_ITEM_ID);
sURIMatcher.addURI(AUTHORITY, "item", ITEMS);
sURIMatcher.addURI(AUTHORITY, "item/#", ITEMS_ID);

订单很重要,请在此处阅读我的解释: https://stackoverflow.com/a/15015687/534471