17

My intention is to display the contacts in sorting order using content resolver in android.

For that I'm writing:

Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?", new String[] { id }, null);

It needs that the last parameter in query method should not be null for sorting the elements by Name. Which part of code I have to replace the null parameter to achieve sorting by name?

phrogg
  • 888
  • 1
  • 13
  • 28
user1862773
  • 173
  • 1
  • 1
  • 5

5 Answers5

39

To sort result according to name use Phone.DISPLAY_NAME constant with ASC as last parameter to query method. do it as:

  Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                   null, 
                   ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?",
                   new String[] { id },
                   ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
15

It would be better to use SORT_KEY_PRIMARY or SORT_KEY_ALTERNATIVE on API level 11 and later.

Cursor cursor = getContentResolver().query(
    ContactsContract.Contacts.CONTENT_URI,
    null, null, null,
    ContactsContract.Contacts.SORT_KEY_PRIMARY + " ASC");
Nick Dowell
  • 2,030
  • 17
  • 17
14

You can use Upper() to sort for both lower as well as upper case contact name.

ContentResolver cr = getContentResolver();

Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
        null, null,  "upper("+ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") ASC");
Akhilesh Dhar Dubey
  • 2,152
  • 2
  • 25
  • 39
  • Does a standard sorting method (not using upper) give weight to uppercase letters? Like will names in all caps be BEFORE names in lowercase? If so, is that the reason behind your "upper(" line of code? If not, what does this do? – PGMacDesign Jul 12 '16 at 16:19
1

The ContentResolver.query() method takes many arguments but to sort the content provider records, you have to edit the last argument of this method.

enter image description here

It should be like this:

Cursor cursor=getContentProvider().query(.......,"DISPLAY_NAME ASC")

This will arrange the contacts in Ascending order of their name.

Note: This argument should be in a String datatype.

dippas
  • 58,591
  • 15
  • 114
  • 126
Prateek Sharma
  • 312
  • 3
  • 5
0

You can use the Desc string using these lines to sort out to see the recent contact

    android.database.Cursor cursor = getContentResolver()
            .query(android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null, null, null,
                    ContactsContract.Data.CONTACT_LAST_UPDATED_TIMESTAMP +" DESC");