Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a contact's number from contact name in android

Tags:

android

I am having a contacts name with me and want his number .How to get contact number of corresponding name in Android ?

like image 338
Sando Avatar asked Jun 13 '11 12:06

Sando


2 Answers

A shorter version; you still need that permission (android.permission.READ_CONTACTS)

public String getPhoneNumber(String name, Context context) {
String ret = null;
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        projection, selection, null, null);
if (c.moveToFirst()) {
    ret = c.getString(0);
}
c.close();
if(ret==null)
    ret = "Unsaved";
return ret;
}
like image 179
Umut Shn Avatar answered Oct 02 '22 22:10

Umut Shn


The following code will log out to logcat all the mobile numbers for a contact with a display name of contactName:

Cursor cursor = null;
try {
    cursor = getContentResolver().query(Data.CONTENT_URI,
            new String [] { Data.RAW_CONTACT_ID },
            StructuredName.DISPLAY_NAME + "=? AND "
                + Data.MIMETYPE + "='" + StructuredName.CONTENT_ITEM_TYPE + "'",
            new String[] { contactName},  null);
    if (cursor != null && cursor.moveToFirst()) {
        do {
            String rawContactId = cursor.getString(0);
            Cursor phoneCursor = null;
            try {
                phoneCursor = getContentResolver().query(Data.CONTENT_URI,
                        new String[] {Data._ID, Phone.NUMBER},
                        Data.RAW_CONTACT_ID + "=?" + " AND "
                                + Phone.TYPE + "=" + Phone.TYPE_MOBILE + " AND "
                                + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
                                new String[] {rawContactId}, null);

                if (phoneCursor != null && phoneCursor.moveToFirst()) {
                    String number = phoneCursor.getString(phoneCursor.getColumnIndex(Phone.NUMBER));
                    Log.d(TAG, "Mobile Number: " + number);
                }
            } finally {
                if (phoneCursor != null) {
                    phoneCursor.close();
                }
            }
        } while (cursor.moveToNext());  
    }
} finally {
    if (cursor != null) {
        cursor.close();
    }
}
like image 31
Nic Strong Avatar answered Oct 02 '22 22:10

Nic Strong