Search code examples
androiduriandroid-contentprovider

UriMatcher not recognizing pattern


I'm having trouble with matching URIs in my ContentProvider. It will match paths with one or two "tags" (not sure what the correct term is), for example it can recognize box/#. But as soon as I add a second tag, for example box/#/item, I throw an InvalidArgumentException and my app crashes. I've read in several threads on here that this issue can sometimes be solved by changing the order of the URIs added to the UriMatcher; I tried this, but to no avail. Anyone know what the problem is? I've excerpted relevant parts of my code below.

From my 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);
}

An example of where I try to access my ContentProvider and it fails:

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

Solution

  • Try this:

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

    The order is important, read my explanations here: https://stackoverflow.com/a/15015687/534471