Get contact ID with the given contact name. - Android Account

Android examples for Account:Contact Name

Description

Get contact ID with the given contact name.

Demo Code


//package com.java2s;

import android.content.Context;

import android.database.Cursor;

import android.provider.ContactsContract;

public class Main {
    /**//from  w w  w.j a v a 2  s  . c om
     * Get contact ID with the given contact name.
     *
     * @param name      Name of the contact.
     * @param context   Context object of the caller.
     * @return          Contact ID.
     */
    public static long getContactId(String name, Context context) {
        long ret = -1;
        String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                + " like'%" + name + "%'";
        String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.CONTACT_ID };
        Cursor c = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                projection, selection, null, null);
        if (c.moveToFirst()) {
            ret = c.getLong(0);
        }
        c.close();

        return ret;
    }
}

Related Tutorials