Search code examples
androiddatetimecharacter-encodinguriandroid-contentprovider

Android ContentProvider, URI with spaced (Date in YYYY-MM-DD HH:MM:SS)


I consider what is best practice for parsing String to Uri that can be used with ContentProvider. This Uri should contain DateTime in format YYYY-MM-DD HH:MM:SS.

'content://authority/basepath/someId/12/date/YYYY-MM-DD HH:MM:SS'

I can make on this date String.replace(' ', '+'); and then uri.getPathSegments().get(4).replace('+', ' ')

But maybe there is some better approach to this problem?

It seems that such URI isn't matched by UriMatcher in ContentProvider.update()

content://com.xxx.provider.XXXProvider/learning_stats/profile/1/access_date/2015-04-08+11:40:24

and this is my UriMatcher definition:

uriMatcher.addURI(AUTHORITY, BASE_PATH + "/profile/#/access_date/#", ROW_FOR_PROFILE_AND_ACCESS_DATE);

Solution

  • Firstly, in UriMatcher, "#" means numbers, "*" means text or exact. Check the source code in /frameworks/base/core/java/android/content/UriMatcher.java

    I don't think there's necessary to do the replacement, Uri Builder would encode your date string,

        Uri uri = new Uri.Builder().scheme("content").path("/authority/basepath/someId/12/date/YYYY-MM-DD HH:MM:SS").build();
        String date = uri.getPathSegments().get(5);
    

    The encoded path is,

    /authority/basepath/someId/12/date/YYYY-MM-DD%20HH%3AMM%3ASS
    

    As you see, the character ':' should also be replaced, then decoded path is,

    /authority/basepath/someId/12/date/YYYY-MM-DD HH:MM:SS
    

    Or using millisecond value returned from Date.getTime() instead of the Date String.

    'content://authority/basepath/someId/12/date/12345434'
    

    getTime() Returns this Date as a millisecond value. The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.

    It's easy to parse the time,

    Date time = new Date(12345434l);//12345434 is the value from URI.