Android搜索联系人按电话号码和联系人姓名(两者同时)

时间:2017-08-16 11:29:03

标签: android

我想通过电话号码和联系人姓名同时查询联系人" LIKE"运算符,这是我的代码:

    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1 AND (" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " LIKE '" + query + "%' OR " + ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE '%" + query + "%' OR " + ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE '%" + query + "%' ) ", null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    return cursor;

但是我的代码不起作用,它的崩溃和安卓说的" data4"和" data1"列不存在。

2 个答案:

答案 0 :(得分:1)

使用以下代码按名称查找联系人

public String findByName(Context context , String name) {  
   String result= null;
            String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
            String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER};
            Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    projection, selection, null, null);
            if (c.moveToFirst()) {
                result= c.getString(0);
            }
            c.close();
            if(result==null)
                result= "This contact is not saved into your device";
            return result;
}

答案 1 :(得分:0)

使用加载程序获得最快的结果。

public Loader<Cursor> getContactCursor(Context context, Bundle args) {
        Uri baseUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;  
        String filter = args != null ? args.getString("filter") : null;
        if (filter != null && filter.length() > 0) {
            return new CursorLoader(context,baseUri, null, "(display_name LIKE ?) OR (data1 LIKE ?)", new String[]{"%" + filter + "%","%" + filter + "%"}, null);
        }else{
            return new CursorLoader(context,baseUri, projection,null, null, null);
        }

    }