views:

68

answers:

2

Hello,

Assuming I have a contact saved in my addressbook, called "TomTasche" with the mail-address "[email protected]". 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 + " = " + "[email protected]", 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" <[email protected]>)

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

06-22 09:21:14.260: [...] AND (data1 = "Tom" <[email protected]>)

So, how am I able to retrieve the name?

Thanks
Tom

edit:

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

+2  A: 

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("[email protected]"));
Cursor cur = getContentResolver().query(uri, new String[]{Email.CONTACT_ID, mail.DISPLAY_NAME, Email.TYPE, Phone.DISPLAY_NAME}, null, null, null);
Gawcio
Thanks that works!
TomTasche
A: 

Another solution somebody told me via Twitter:

http://twitter.com/maxrayman/status/16775869807

Works too.

TomTasche