Limit number of rows in Cursor query

☆樱花仙子☆ 提交于 2020-01-04 04:12:06

问题


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.


回答1:


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



回答2:


Order by id DESC Limit 1:

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



回答3:


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


来源:https://stackoverflow.com/questions/20962528/limit-number-of-rows-in-cursor-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!