Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit number of rows in Cursor query

I need to get contacts from an android phone. so I am using this code:

Cursor phones = getActivity().getContentResolver().query(Phone.CONTENT_URI,
    new String[] { Phone.NUMBER, Phone.TYPE },
    " DISPLAY_NAME = ?", new String[] { displayName }, null);
while (phones.moveToNext()) {
   //do work here
}

I want to tell the cursor to limit the response to 50 with something like "LIMIT 50". Where do I pass that information to the cursor? Please copy and paste my code and make edit there.

like image 947
user3093402 Avatar asked Oct 25 '25 08:10

user3093402


2 Answers

There is no limit in Android API, but you can apply it in your code like this:

Cursor phones = getActivity().getContentResolver().query(Phone.CONTENT_URI,
    new String[] { Phone.NUMBER, Phone.TYPE },
    " DISPLAY_NAME = ?", new String[] { displayName }, null);
for (int i = 0; i < 50 && phones.moveToNext(); ++i) {
   // do work here
}
phones.close();
like image 52
flx Avatar answered Oct 26 '25 21:10

flx


If you have the DB and the table name you can use that, but Content providers don't have a limit argument in their query statement.

mDb = new DBHelper (this);

Cursor c = mDB.getReadableDatase().query(
       <Phone_Table_Name>, 
       new String[] { Phone.NUMBER, Phone.TYPE }, 
       "DISPLAY_NAME = ?", 
       new String[] { displayName }, null), 
       null, 
       null, 
       null, 
       "50");
like image 33
Cory Roy Avatar answered Oct 26 '25 21:10

Cory Roy