Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limiting number of rows in a ContentResolver.query() function

Is there a way to limit the number of returned rows to a cursor? I have a phone with about 4000 contacts, I just need some of them.

this is the code i'm using

        db = new dBHelper(this);         ContentResolver cr = getContentResolver();         Cursor cursor;          cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, ContactName + " ASC");         Log.i(TAG, CLASSNAME + " got contacts entries");         for (int it = 0; it <100 ; it++){//cursor.getCount()             Log.i(TAG, CLASSNAME + " getting string");             String mytimes_contacted = cursor.getString(cursor.getColumnIndex(dBHelper.times_contacted));              Log.i(TAG, CLASSNAME + " done from the string");         } 

the Log i'm getting is

I/Check(11506): [ContactsPicker] got contacts entries I/Check(11506): [ContactsPicker] getting first string D/AndroidRuntime(11506): Shutting down VM W/dalvikvm(11506): threadid=1: thread exiting with uncaught exception (group=0x2aac8578) D/dalvikvm(11541): GC_CONCURRENT freed 923K, 46% free 4000K/7303K, external 1685K/2133K, paused 1ms+8ms E/AndroidRuntime(11506): FATAL EXCEPTION: main E/AndroidRuntime(11506): java.lang.RuntimeException: Unable to start activity ComponentInfo{~~my package name~~}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 3537 
like image 389
user1347945 Avatar asked Apr 30 '12 21:04

user1347945


People also ask

What does Contentresolver query () return?

It returns just an empty cursor.

What is Contentresolver?

The Content Resolver behaves exactly as its name implies: it accepts requests from clients, and resolves these requests by directing them to the content provider with a distinct authority. To do this, the Content Resolver stores a mapping from authorities to Content Providers.


2 Answers

To limit the number of results in your cursor try:

cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, ContactName + " LIMIT 100"); while(cursor.moveToNext()) {     // something clever } 
like image 164
Sam Avatar answered Sep 25 '22 14:09

Sam


The accepted answer is not valid anymore for android 11. In android 11 a constraint was added to not allow using LIMIT in sort value. You need to use the query with bundle parameters. For instance:

        val bundle = Bundle().apply {             putInt(ContentResolver.QUERY_ARG_LIMIT, 100)         }         resolver.query(                 ContactsContract.Contacts.CONTENT_URI,                 projection,                 bundle,                 null         ) 
like image 30
Ignacio Tomas Crespo Avatar answered Sep 25 '22 14:09

Ignacio Tomas Crespo