user3093402
user3093402

Reputation: 1469

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.

Upvotes: 4

Views: 3311

Answers (3)

Cory Roy
Cory Roy

Reputation: 5609

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");

Upvotes: 1

flx
flx

Reputation: 14226

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();

Upvotes: 2

allsoft
allsoft

Reputation: 198

Order by id DESC Limit 1:

db.query("table", null, "column=?", new String[]{"value"}, null, null, "id DESC", "50");

Upvotes: 0

Related Questions