get Contact Number - Android Account

Android examples for Account:Contact Number

Description

get Contact Number

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 getContactNumber(Context context, String contactUri) {
        String phoneNumber = null;
        Cursor phoneCursor = null;

        try {/*w  ww.  j  a v a 2  s  . c  o  m*/
            String contactId = getContactId(context, contactUri);

            String phoneQuery = ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                    + " = ? AND "
                    + ContactsContract.CommonDataKinds.Phone.TYPE
                    + " = "
                    + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;

            // using the contact ID now we now get contact phone number
            phoneCursor = context
                    .getContentResolver()
                    .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER },
                            phoneQuery, new String[] { contactId }, null);

            if (phoneCursor.moveToFirst()) {
                phoneNumber = phoneCursor
                        .getString(phoneCursor
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }

            phoneCursor.close();
        } finally {
            if (phoneCursor != null) {
                phoneCursor.close();
            }
        }

        return phoneNumber;
    }

    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