Published 19 Sep, 2022

Java - Meaning of android.content.UriMatcher

Category Java
Modified : Oct 03, 2022

What is Uri Matcher in android.content.UriMatcher

How to use it? Can someone please explain meaning of following three line of code?

  uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  uriMatcher.addURI(PROVIDER_NAME, "cte", uriCode);
  uriMatcher.addURI(PROVIDER_NAME, "cte/*", uriCode);
  int res = uriMatcher.match(uri);


There are 3 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Java, Android, Uri. These have been categorized in sections for a clear and precise explanation.


UriMatcher is a handy class when you are writing a ContentProvider or some other class that needs to respond to a number of different URIs. In your example, a user could query your provider with URIs such as:




When you construct a UriMatcher, you need to have separate codes for each URI (not just "uriCode" as in your example). I usually make my UriMatcher instance static, and add the URIs in a static constructor:

private static final int CTE_ALL = 1;
private static final int CTE_FIND = 2;
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
    uriMatcher.addURI(PROVIDER_NAME, "cte", CTE_ALL);
    uriMatcher.addURI(PROVIDER_NAME, "cte/*", CTE_FIND);

Then in your ContentProvider you would do something like this in your query method:

Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    int res = uriMatcher.match(uri);
    switch (res) {
        case CTE_ALL:
            //TODO create a results Cursor with all the CTE results
        case CTE_FIND:
            //TODO create a results Cursor with the single CTE requested
    return results;


I found the following videos to be useful:

URI Basics

URI Matcher

In essence, what you are trying to do is, have an ID or a number associated to different URIs. When you use addUri, a code/number/ID gets created against the URI. When you request a match(), the corresponding code is returned.


One more thing I wanted to add that wasn't clear for me first time I used UriMatcher.

Is that if you want to parse an HTTP url then as an AUTHORITY parameter in the addURI you need to pass the target domain name. For example:

Uri mUri = Uri.parse("");
UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);

// if not "" below the match will always return -1 result
sURIMatcher.addURI("", "/foo", 123);

int match = sURIMatcher.match(mUri);

UriMatcher Documentation doesn't cover this case and it's not clear what's this authority parameter for. Gosh if I knew that it would save me some time!