1

I would like to limit the amount of contacts displayed in my app. Currently it is querying my Contactscontract.Contacts DB and returning every primary display name that has a phone number. Is there a simple way to reduce this to a numerical amount (say only display 5 contacts), or to certain specified ID's?

This is what I have so far:

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

    // load from the "Contacts table"
    Uri contentUri = ContactsContract.Contacts.CONTENT_URI;

    // no sub-selection, no sort order, simply every row
    // projection says we want just the _id and the name column
    return new CursorLoader(getActivity(),
            contentUri,
            PROJECTION,
            ContactsContract.Contacts.HAS_PHONE_NUMBER + " =?", // This is selection string, were looking for records that HAS_PHONE_NUMER is 1
            new String[]{"1"}, // 1 means that contact has a phone number
            ContactsContract.Contacts._COUNT,
            new String[] {"5"},
            null);
}

Whenever I try to add new parameters in the return section, Android Studio immediately goes red saying cannot resolve constructor. Is this because the CursorLoader is not defined to receive more parameters?

I defined it earlier in my code as:

mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);

Cheers, Shyam

Shyam
  • 151
  • 1
  • 2
  • 7
  • Is the answer perhaps reliant on creating an arraylist and then applybatch() deleting all the unwanted items? – Shyam Apr 27 '15 at 00:33

1 Answers1

0

To achieve a limitation of query results, please add (string concatenate) a " LIMIT 5" to your query:

...
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=? LIMIT 5" //This is selection string, were looking for records that HAS_PHONE_NUMER is 1 AND 
// the result set is limited to 5 rows
new String[]{"1"},
null);
...
xerx593
  • 12,237
  • 5
  • 33
  • 64
  • Thank you - that seems to be the methodology I need to use. However, for some reason the app keeps on crashing whenever I query COUNT. I have made sure that I also included it in the initialization of my projection. Do you know any other variables that may fulfill this task? – Shyam Apr 27 '15 at 01:26
  • up-to-date, @Shyam, see: http://stackoverflow.com/a/6361710/592355, http://stackoverflow.com/a/2497689/592355, http://stackoverflow.com/q/13690281/592355 – xerx593 Apr 27 '15 at 01:37