0

I want to implement search the contacts on basis of number provided.

I have used ContactsContract to read all the contacts. I have implemented search criteria on basis of name by proving a searchView and the matching name will be displayed but I want to do the same by number also

private List<ContactItem> getContacts(String s) {
    String whereString = "display_name LIKE ?";
    String[] whereParams = new String[]{ "%" + s + "%"};
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, whereString, whereParams, null);
    List<ContactItem> contacts = new ArrayList<>();
    assert cur != null;
    while (cur.moveToNext()) {

        String name = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        contacts.add(new ContactItem(name,phoneNumber));
    }
    cur.close();
    return contacts;
}

I want to use phone number instead of display_name here. How to do that

M Reza
  • 18,350
  • 14
  • 66
  • 71
  • see `ContactsContract.CommonDataKinds.Phone#CONTENT_FILTER_URI` - *"The content:// style URL for phone lookup using a filter. The filter returns records of MIME type CONTENT_ITEM_TYPE. The filter is applied to display names as well as phone numbers. The filter argument should be passed as an additional path segment after this URI."* – pskink Jan 20 '19 at 19:18

1 Answers1

0

Try the following code, should filter based on both name and number:

private List<ContactItem> getContacts(String numberOrName) {
    Uri searchUri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(numberOrName));

    String[] projection = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER };
    Cursor cur = getContentResolver().query(searchUri, projection, null, null, null);

    List<ContactItem> contacts = new ArrayList<>();
    assert cur != null;
    while (cur.moveToNext()) {

        String name = cur.getString(0);
        String phoneNumber = cur.getString(1);

        contacts.add(new ContactItem(name, phoneNumber));
    }
    cur.close();
    return contacts;
}
marmor
  • 27,641
  • 11
  • 107
  • 150