使用部分号码联系查找

时间:2017-12-14 12:02:15

标签: android

我试图通过部分号码进行联系人查询,尝试了多种方法,包括此处描述的方法:https://www.reddit.com/r/androiddev/comments/2ysulf/contact_lookup_by_partial_phone_number/但我的列表中仍有数字不会显示在这些方法。

这些数字的分隔符如下:" 00 1 963-899-6889"在ContactsContract.Data.CONTENT_URI表中,ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER列为NULL。

但是,如果我尝试使用完整匹配方法:https://developer.android.com/reference/android/provider/ContactsContract.PhoneLookup.html搜索查询=" 9638996889"(没有分隔符的数字),它会找到它。

这是完整匹配查询的结果行:

number: 00 1 963-899-6889
contact_id: 136
photo_uri: null
phonebook_label: …
send_to_voicemail: 0
is_autorecording: 0
data_id: 931
lookup: 654i6dbdb5460ae0585c
display_name: _Teste
last_time_contacted: 0
has_phone_number: 1
in_visible_group: 1
photo_file_id: null
label: null
starred: 0
normalized_number: null
photo_thumb_uri: null
in_default_directory: 1
photo_id: null
custom_ringtone: null
_id: 136
type: 3
times_contacted: 0

编辑:通过查询完整的ContactsContract.Data表并在selectionClause中放入一堆替换来忽略那些分隔字符,找到了一种简洁的解决方法:

REPLACE(REPLACE(REPLACE(REPLACE(name, '-', ''), '(', ''),')',''), ' ', '')

1 个答案:

答案 0 :(得分:0)

也许对某人有所帮助:我已经通过在搜索查询中的每个字符后添加%解决了这个问题,因此对于'123'输入,我们有'%1%2%3%'查询。我的查找逻辑示例:

// entered query from EditText    
private String cursorFilter;

...

public Loader<Cursor> contactsLoader() {
    Uri contactsUri = ContactsContract.Data.CONTENT_URI;

    String[] projection = new String[]{ContactsContract.Data.CONTACT_ID,
            ContactsContract.Data.DISPLAY_NAME,
            ContactsContract.Data.MIMETYPE,
            ContactsContract.Data.DATA1,
            ContactsContract.Data.DATA2,
            ContactsContract.Data.DATA3};

    String selection = ContactsContract.Data.MIMETYPE + " IN ('"
            + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "')";

    String[] selectionArgs = {};
    String sortOrder = null;

    if (cursorFilter != null && !cursorFilter.isEmpty()) {
        // check is input digit or not
        char c = cursorFilter.charAt(0);
        if (Character.isDigit(c)) {
            // search through Phone.NUMBER
            String queryFilter = " AND " + ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE ?";

            selectionArgs = new String[]{buildDigitFilter()};
            selection += queryFilter;
        } 
    }

    return new CursorLoader(
            сontext,
            contactsUri,
            projection,
            selection,
            selectionArgs,
            sortOrder);
}

private String buildDigitFilter() {
    StringBuilder filterBuilder = new StringBuilder("%");

    for (int i = 0; i < cursorFilter.length(); i++) {
        filterBuilder.append(cursorFilter.charAt(i))
                .append("%");
    }

    return filterBuilder.toString();
}