如何在ContactsContract查询中使用数字实现搜索联系人。就像“ display_name喜欢吗?”为了名字

时间:2019-01-20 17:38:21

标签: android android-contacts contactscontract

我想根据提供的电话号码来搜索联系人。

我已经使用ContactsContract来读取所有联系人。我已经通过证明一个searchView来实现了基于名称的搜索条件,并且匹配的名称会显示出来,但是我也想按数字进行同样的操作

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;
}

我想在这里使用电话号码而不是display_name。怎么做

1 个答案:

答案 0 :(得分:0)

尝试以下代码,应根据姓名和电话号码进行过滤:

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;
}