联系人中存在联系人

时间:2012-04-01 15:57:10

标签: android

我有电话号码。有没有办法检查设备中的联系人数据库中是否存在电话号码?根据我的需要,我的应用程序进一步移动。请建议或者如果有人可以提供示例代码段,请提供。

以下是我写的代码:

public boolean contactExists(Activity _activity, String number) {
    String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
    Cursor cur = _activity.getContentResolver().query(number, mPhoneNumberProjection, null, null, null);
    try {
        if (cur.moveToFirst()) {
            return true;
        }
    } finally {
        if (cur != null)
            cur.close();
    }
    return false;
}// contactExists

提前致谢...

3 个答案:

答案 0 :(得分:18)

public boolean contactExists(Activity _activity, String number) {
    if (number != null) {
        Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
        String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
        Cursor cur = _activity.getContentResolver().query(lookupUri, mPhoneNumberProjection, null, null, null);
        try {
            if (cur.moveToFirst()) {
                return true;
            }
        } finally {
            if (cur != null)
                cur.close();
        }
        return false;
    } else {
        return false;
    }
}// contactExists

处理nullpointer异常。

答案 1 :(得分:3)

代码中的微小变化:: 你需要有lookupUri ..

public boolean contactExists(Activity _activity, String number) {
    Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
    Cursor cur = _activity.getContentResolver().query(lookupUri, mPhoneNumberProjection, null, null, null);
    try {
        if (cur.moveToFirst()) {
            return true;
        }
    } finally {
        if (cur != null)
            cur.close();
    }
    return false;
}// contactExists

答案 2 :(得分:0)

我在冰淇淋设备(SIII)上尝试了上面的代码,但它没有用 所以经过一些搜索我最终创建了这个方法(这很好用)

    private boolean isContact(String incommingNumber) {
        Cursor cursor =null;
        String name = null;
        try {
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(incommingNumber));
             cursor = MainService.this.getContentResolver().query(uri, new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                name = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
            }
        } finally {
            if(cursor!=null){
                cursor.close();
            }
        }
        return Util.hasValue(name);
    }