Monday, January 9, 2012

Using LIMIT with android ContentProvider

So you're using a content provider in your android app, and you want to supply a LIMIT parameter. The problem is, ContentProvider's query method doesn't have a limit parameter. Well, fortunately there's an easy solution; put the limit into a query parameter:
  1. First, in your content provider, create a constant for the query parameter key:
    public class MyProvider extends ContentProvider {
        public static final String QUERY_PARAMETER_LIMIT = "limit";

  2. In the query method of your content provider, get the limit from the Uri:
    public Cursor query(...
        String limit = uri.getQueryParameter(QUERY_PARAMETER_LIMIT);

  3. Still in the query method of your content provider, you can pass the limit on when creating the cursor:
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder, limit);

  4. Lastly, when calling your content provider (via getContentResolver.query(), a CursorLoader, etc), you can append the limit to the content uri like so:
    String someLimit = "15";
    cursor = getContentResolver().query(
        // add the limit to the content uri
        MyProvider.CONTENT_URI.buildUpon().appendQueryParameter(
            MyProvider.QUERY_PARAMETER_LIMIT,
            someLimit).build(),
            ...
The cool thing is you can use this same technique to pass other parameters to your query, like DISTINCT, for instance.

3 comments:

  1. Very useful, thanks!

    ReplyDelete
  2. It would be really great if you could share sample code

    ReplyDelete
  3. I googled QUERY_PARAMETER_LIMIT and found these, which might be helpful:

    https://code.google.com/p/dnd-aac/source/browse/trunk/dnd-aac/src/com/dnd/aac/data/aacProvider.java
    https://code.google.com/p/dnd-aac/source/browse/trunk/dnd-aac/src/com/dnd/aac/util/SuggestHelper.java

    ReplyDelete