get Contact Id By Email Address - Android Account

Android examples for Account:Contact ID

Description

get Contact Id By Email Address

Demo Code


import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;

public class Main{
    public static long getIdByEmailAddress(Context context,
            String emailAddress) {
        Log.d(EmailPopup.LOG_TAG, "getIdByEmailAddress(): " + emailAddress);
        if (emailAddress == null || emailAddress.equals("")) {
            return -1;
        } else {/*from   ww w  .  java2  s  .  c o  m*/
            long contactId;
            Uri uri = Uri
                    .withAppendedPath(
                            ContactsContract.CommonDataKinds.Email.CONTENT_LOOKUP_URI,
                            Uri.encode(emailAddress.trim()));
            Cursor cursor = context
                    .getContentResolver()
                    .query(uri,
                            new String[] { ContactsContract.CommonDataKinds.Email.CONTACT_ID },
                            null, null, null);

            if (cursor != null) {
                try {
                    if (cursor.getCount() > 0) {
                        cursor.moveToFirst();
                        contactId = Long.valueOf(cursor.getLong(0));
                        Log.d(EmailPopup.LOG_TAG,
                                "Found contactId by email address: "
                                        + contactId);
                    } else {
                        Log.v(EmailPopup.LOG_TAG, "Count = 0");
                        contactId = -1;
                    }
                } finally {
                    cursor.close();
                }
            } else {
                Log.v(EmailPopup.LOG_TAG, "Cursor is null");
                contactId = -1;
            }

            return contactId;
        }
    }
}

Related Tutorials