Search code examples
androidandroid-contentprovider

What is the proper way to get data from content provider once you have the row uri?


I was wondering if it is possible to get the data which is present in a content provider row directly in a cursor (or other container) in the case where I already know the row uri (in other words, I already have the ContentURIs with the row id appended).

Both an insert or a Content Observer OnChange (on android api 16) gives me back the inserted/changed URI and I would like to get the data from that row efficiently (without many queries or instructions). However, the only way I found was to parse the ID from the URI, build a query with a selection clause to that id and then get the cursor, as:

     long row = ContentUris.parseId(uri);
     String mSelectionClause = ContentProvider.Table._ID + " = ?";
     String[] mSelectionArgs = {Long.toString(row)};
     Uri other_uri = Uri.parse(ContentProvider.AUTHORITY_STRING + ContentProvider.UriPathIndex.Table);
     Cursor cursor = cr.query(other_uri ,null,mSelectionClause,mSelectionArgs,null);

Is there some other way of doing it? I was wondering if it was possible to directly use the row uri


Solution

  • Citing from http://developer.android.com/guide/topics/providers/content-provider-basics.html#ContentURIs

    Many providers allow you to access a single row in a table by appending an ID value to the end of the URI. For example, to retrieve a row whose _ID is 4 from user dictionary, you can use this content URI:

    Uri singleUri = ContentUris.withAppendedId(UserDictionary.Words.CONTENT_URI,4);
    

    EDIT (from comments): It works for all the standardized content providers (at least those provided by Google). It will work for all content providers which follow the design guidelines for content providers backed up by a row-based data store.