5

我试图检查联系人列表中存在的号码,我使用下面的代码,但我总是在这一行得到错误

 Cursor cur = this.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);

谁能帮我找出问题所在,我已经允许在清单中阅读我的联系人

  public String getContactName(String number)
{
    String name = null;
    Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
    Cursor cur = this.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
    try 
    {
       if (cur.moveToFirst())
       {
           name = cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME));
           return name;
       }
    }
    finally 
    {
    if (cur != null)
       cur.close();
    }
    return "unknown number";
}

这是我的错误日志!错误日志

4

2 回答 2

8

试试这个代码:(使用上下文)

public boolean contactExists(Context context, String number) {
    /// number is the phone number
    Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
    Cursor cur = context.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
    try {
        if (cur.moveToFirst()) {
            return true;
        }
    }
    finally {
        if (cur != null){
            cur.close();
        }
        return false;
    }
}
于 2013-03-22T09:08:46.603 回答
1

这个对我有用。处理 NullPointerException。

public boolean contactExists(Context context, String number) {
    if (number != null) {
        ContentResolver cr = context.getContentResolver();
        Cursor curContacts = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

        while (curContacts.moveToNext()) {
            String contactNumber = curContacts.getString(curContacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            if (number.equals(contactNumber)) {
                return true;
            }
        }
        return false;
    } else {
        return false;
    }
}
于 2019-07-05T18:20:46.463 回答