get Contact Id By Name - Android Account

Android examples for Account:Contact Name

Description

get Contact Id By Name

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 getIdByName(Context context, String name) {
        Log.d(EmailPopup.LOG_TAG, "getIdByName(): " + name);
        if (name == null || name.equals("")) {
            return -1;
        } else {//from   ww w.  j  a va 2s .  c  om
            long contactId;
            Cursor cursor = context.getContentResolver().query(
                    ContactsContract.Contacts.CONTENT_URI,
                    new String[] { ContactsContract.Contacts._ID },
                    ContactsContract.Contacts.DISPLAY_NAME + " = ?",
                    new String[] { name.trim() }, 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 name: " + name);
                    } 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