Contact exists in contacts

I have a phone number. Is there a way to check if a phone number exists in the contacts database on the device or not? Depending on this, I need to move on in my application. Please suggest, or if anyone has a sample code snippet, please provide.

Below is the code I wrote:

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 

Thanks in Advance ...

+7
source share
3 answers
 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 exception handled.

+17
source

A small change in your code :: You need to have 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 
+3
source

I tried the code above on an ice cream device (SIII) and it didn’t work so after some searching I finished creating this method (which works beautifully)

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

All Articles