1

Assuming I have a contact saved in my addressbook, called "TomTasche" with the mail-address "stackoverflow@gmail.com". How can I retrieve the contact's name, if I only know the mail-address?

I already asked a similar questions about retrieving contact's nickname here, but if I change that code to query the mail, like that:

Cursor cur = context.getContentResolver().query(Email.CONTENT_URI, new String[] {Email.DISPLAY_NAME, Email.TYPE, Email.CONTACT_ID}, Email.DATA + " = " + "stackoverflow@gmail.com", null, null);

final int nameIndex = cur.getColumnIndex(Email.DISPLAY_NAME);
final int typeIndex = cur.getColumnIndex(Email.TYPE);
final int idIndex = cur.getColumnIndex(Email.CONTACT_ID);

if (cur.moveToFirst()) {
    name = cur.getString(nameIndex);
    type = cur.getString(typeIndex);
    id = cur.getString(idIndex);
} else {
    name = UNKNOWN;
}

it forces close and logcat tells me that there's a syntax error near @gmail.

06-22 09:21:14.260: ERROR/DatabaseUtils(110): Writing exception to parcel
06-22 09:21:14.260: ERROR/DatabaseUtils(110): android.database.sqlite.SQLiteException: near "@gmail": syntax error: , while compiling: SELECT display_name, data2, contact_id FROM view_data_restricted data WHERE (1 AND mimetype = 'vnd.android.cursor.item/phone_v2') AND (data1 = "Tom" <stackoverflow@gmail.com>)

Interesting is that it seems to query fine. Logcat prints out the contact's name:

06-22 09:21:14.260: [...] AND (data1 = "Tom" <stackoverflow@gmail.com>)

So, how am I able to retrieve the name?

Thanks
Tom

edit:

Syntax Error is caused by missing quotes, but cursor returns null anyway.

Community
  • 1
  • 1
TomTasche
  • 5,448
  • 7
  • 41
  • 67

1 Answers1

6

Use Phone.DISPLAY_NAME instead of Email.DISPLAY_NAME in both query() and getColumnIndex() (first 2 lines).

edit:

There's also special uri for e-mail lookups: Email.CONTENT_LOOKUP_URI. It seems to be more convenient in use (no need to put quotas or manually compose selection argument as in your code):

Uri uri = Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode("stackoverflow@gmail.com"));
Cursor cur = getContentResolver().query(uri, new String[]{Email.CONTACT_ID, mail.DISPLAY_NAME, Email.TYPE, Phone.DISPLAY_NAME}, null, null, null);
Gawcio
  • 1,125
  • 1
  • 9
  • 17