如何使用部分电话号码搜索android中的联系人

问题描述 投票:1回答:1

我正在尝试使用部分电话号码对我的Android应用程序中的联系人进行模糊搜索,代码如下。但我的搜索功能总是没有结果。

例如,

我联系了电话号码1234567890,名称为“example”。

fuzzySearch("4567");应该返回名为“example”的联系人。

有人可以指点我在哪里错了吗?我检查了here。但结束于运行时sql查询错误。

public ArrayList<Contact> fuzzySearch(String match) {
    private static final String SELECTION = Phone.NUMBER + " LIKE ? COLLATE NOCASE";

    Uri uri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(match));

    String[] projectionFields = new String[]{ContactsContract.Contacts._ID, Phone.NUMBER};

    CursorLoader cursorLoader = null;

    ArrayList<Contact> listContacts = new ArrayList<>();

    if(match.trim().length() == 0){
       return listContacts;
    }else {
        cursorLoader = new CursorLoader(context, uri, projectionFields, SELECTION, new String[]{"%"+match+"%"}, Phone.NUMBER);
    }

    Cursor c = cursorLoader.loadInBackground();

    final Map<String, Contact> contactsMap = new HashMap<>(c.getCount());

    if (c.moveToFirst()) {
        int idIndex = c.getColumnIndex(ContactsContract.Contacts._ID);
        int nameIndex = c.getColumnIndex(Phone.NUMBER);

        do {
            String contactId = c.getString(idIndex);
            String contactDisplayName = c.getString(nameIndex);
            Contact contact = new Contact(contactId, contactDisplayName);
            contactsMap.put(contactId, contact);
            listContacts.add(contact);
        } while (c.moveToNext());
    }

    c.close();
    return listContacts;
}
android android-contentprovider android-contacts android-cursorloader
1个回答
0
投票

使用PhoneLookup而不是手机。因为您已经将搜索关键字编码到URL中,所以您不需要选择,删除它。

   Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(match));
   Cursor cur = resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME,PhoneLookup.NUMBER, PhoneLookup.CONTACT_ID}, null, null, null);
© www.soinside.com 2019 - 2024. All rights reserved.