Meaning of android.content.UriMatcher

前端 未结 3 990
孤街浪徒
孤街浪徒 2021-02-19 01:08

What is Uri Matcher in android.content.UriMatcher

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

  uriMa         


        
3条回答
  •  南旧
    南旧 (楼主)
    2021-02-19 01:42

    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:

    myprovider://cte
    

    or

    myprovider://cte/somestring
    

    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
                break;
            case CTE_FIND:
                //TODO create a results Cursor with the single CTE requested
                break;
        }
        return results;
    }
    

提交回复
热议问题