get Contact Id From Number - Android Phone

Android examples for Phone:Phone Number

Description

get Contact Id From Number

Demo Code


import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Contacts;

public class Main {
  public static String getContactIdFromNumber(Context context, String number) {
    String[] projection = new String[] { Contacts.People._ID };

    Uri contactUri = Uri.withAppendedPath(Contacts.People.CONTENT_FILTER_URI,
        Uri.encode(getContactNameFromNumber(context, number)));

    Cursor c = context.getContentResolver().query(contactUri, projection, null, null, null);

    if (c.moveToFirst()) {
      String id = c.getString(c.getColumnIndex(Contacts.People._ID));
      return id;//  w w  w .ja  va2s.c  o  m
    }
    return "";
  }

  public static String getContactNameFromNumber(Context context, String number) {
    String[] projection = new String[] { Contacts.Phones.DISPLAY_NAME, Contacts.Phones.NUMBER };

    Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(number));

    Cursor c = context.getContentResolver().query(contactUri, projection, null, null, null);

    if (c.moveToFirst()) {
      String name = c.getString(c.getColumnIndex(Contacts.Phones.DISPLAY_NAME));
      return name;
    }

    // return the original number if no match was found
    return number;
  }
}

Related Tutorials