get Contact Email Address - Android Account

Android examples for Account:Contact Email

Description

get Contact Email Address

Demo Code


//package com.java2s;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;

public class Main {
    public static String getContactEmailAddress(Context context,
            String contactUri) {/*www .  j  a  v  a 2  s.com*/
        String emailAddress = null;
        Cursor emailCursor = null;

        try {
            String contactId = getContactId(context, contactUri);

            // using the contact ID now we now get contact email address
            emailCursor = context.getContentResolver().query(
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Email.CONTACT_ID
                            + " = ?", new String[] { contactId }, null);

            if (emailCursor.moveToFirst()) {
                emailAddress = emailCursor
                        .getString(emailCursor
                                .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            }
        } finally {
            if (emailCursor != null) {
                emailCursor.close();
            }
        }

        return emailAddress;
    }

    public static String getContactId(Context context, String contactUri) {
        String contactId = null;
        Cursor idCursor = null;

        try {
            idCursor = context.getContentResolver().query(
                    Uri.parse(contactUri),
                    new String[] { ContactsContract.Contacts._ID }, null,
                    null, null);

            if (idCursor.moveToFirst()) {

                contactId = idCursor.getString(idCursor
                        .getColumnIndex(ContactsContract.Contacts._ID));
            }
        } finally {
            if (idCursor != null) {
                idCursor.close();
            }
        }

        return contactId;
    }
}

Related Tutorials