5

Android's API provides a clean mechanism via SQLite to make queries into the contact list. However, I am not sure how to limit the results:

Cursor cur = ((Activity)mCtx).managedQuery(
                People.CONTENT_URI,
                columns,
                "LIMIT ? OFFSET ?",
                new String[] { Integer.toString(limit), Integer.toString(offset) },
                null
        );

Doesn't work.

5 Answers5

10

Actually, depending on the provider you can append a limit to the URI as follows:

uri.buildUpon().appendQueryParameter("limit", "40").build()

I know the MediaProvider handles this and from looking at recent code it seems you can do it with contacts too.

dhaag23
  • 6,106
  • 37
  • 35
5

You are accessing a ContentProvider, not SQLite, when you query the Contacts ContentProvider. The ContentProvider interface does not support a LIMIT clause directly.

If you are directly accessing a SQLite database of your own, use the rawQuery() method on SQLiteDatabase and add a LIMIT clause.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
5

I found out from this bug that Android uses the following regex to parse the LIMIT clause of a query:

From <framework/base/core/java/android/database/sqlite/SQLiteQueryBuilder.java>

LIMIT clause is checked with following sLimitPattern.

private static final Pattern sLimitPattern = Pattern.compile("\\s*\\d+\\s*(,\\s*\\d+\\s*)?");

Note that the regex does accept the format offsetNumber,limitNumber even though it doesn't accept the OFFSET statement directly.

Jon O
  • 6,532
  • 1
  • 46
  • 57
  • Thanks for the answer that made my day, week and month! I've been looking for how to pass the "OFFSET" parameter to a database (through a `ContentProvider`) without having to manually query the database (with a `rawQuery(...)` method) for weeks now. – dbm May 03 '11 at 11:53
  • http://www.sqlite.org/lang_select.html (Especially note the very last paragraph on the page) – dbm May 03 '11 at 13:10
  • I'd like to add that if you want to use an offset without limit, use offsetValue, -1 – Michael Simons Dec 25 '13 at 12:33
4

I think you have to do this sort of manually. The Cursor object that is returned from the managedQuery call doesn't execute a full query right off. You have to use the Cursor.move*() methods to jump around the result set.

If you want to limit it, then create your own limit while looping through the results. If you need paging, then you can use the Cursor.moveToPosition(startIndex) and start reading from there.

Andrew Burgess
  • 5,300
  • 5
  • 30
  • 37
4

You can specify the "limit" parameter in the "order" parameter, maybe even inside other parameters if you don't want to sort, because you'll have to specify a column to sort by then:

mContentResolver.query(uri, columnNames, null, null, "id LIMIT 1");
Mark
  • 520
  • 1
  • 7
  • 21