Unable to detect existing phone numbers… here is a solution to the problem.
Unable to detect existing phone numbers
I want to see if a contact exists in the contact database. I came up with this code :
public static boolean contactExists(Activity _activity, String number){
Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(number));
String[] mPhoneNumberProjection = { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER, ContactsContract.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;
}
But it always gives me false, there is a contact on the device.
Also, I’ve integrated permissions into the list.
Solution
I found the error after a few hours, basically it may happen that the above code does not work on some devices. To be 100% sure you need to use this code:
public String get_name() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name + ", ID : " + id);
if (name.equals(number)) {
title_holder = name;
break;
}else{
title_holder = number;
break;
}
}
}
}
return title_holder;
}
As you can see, it lists all the contacts in your device and you can simply check if it matches the number you provided.
Simpler solution:
String myPhone = getCallName.substring(16, getCallName.length() - 4);
if (!myPhone.matches("^[\\d]{1,}$")) {
myPhone = context.getString(R.string.withheld_number);
} else if (listDir.get(i).getUserNameFromContact() != myPhone) {
myPhone = listDir.get(i).getUserNameFromContact();
}