Gangadhar Nimballi Gangadhar Nimballi -4 years ago 130
Android Question

How to get a email for particualr phone number

I want get a email for a particular phone number.

Here is my code

private static String getEmailAndName(String number, Context context) {
String selection = ContactsContract.CommonDataKinds.Phone.NUMBER+" like'%" + number +"%'";
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.DATA};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, selection, null, null);

String aniName = "";
if (c.moveToNext()) {
aniName = c.getString(0);
Log.e(TAG, "Name ====== "+c.getString(0));
Log.e(TAG, "Email ====== "+c.getString(1));
Log.e(TAG, "Email ====== "+c.getString(2));
}
return aniName;
}


But It does not returns email ID. Please help me. Thank you.

Answer Source

Here is the solution:

public static String[] getContactInfo(String phoneNumber, Context context) {
        String info[] = new String[2];

        ContentResolver mResolver = context.getContentResolver();
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));

        Cursor cursor = mResolver.query(uri, new String[] {
                ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID }, null, null, null);

        String contactId = "";
        if (cursor.moveToFirst()) {
            do {
                contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
            } while (cursor.moveToNext());
        }

        //Get Name....
        String[] projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME };
        cursor = mResolver.query(ContactsContract.Contacts.CONTENT_URI, projection,
                ContactsContract.Contacts._ID + "=?", new String[]{contactId}, null);

        String name = "";
        if (cursor.moveToFirst()) {
            name = cursor.getString(0);
        }

        //Get Email Address....
        cursor = mResolver.query(
                ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,
                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",new String[]{contactId}, null);
        String email="";
        while (cursor.moveToNext())
        {
            email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            int emailType = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
        }
        cursor.close();
        info[0] = name;
        info[1] = email;
        return info;
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download