Phone number exists in android contact list

im trying to verify that the number exists in the contact list, I use the code below, but always get an error in this line

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

can someone help me figure out the problem, I gave permission to read my contact in the manifest

  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";
}

this is my error log! error log

+5
source share
2 answers

Try this code: (use context)

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;
}
+6
source

It works for me. NullPointerException thrown.

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;
    }
}
0
source

All Articles