Tim Daiber
Tim Daiber

Reputation: 358

Open Contact information in Contact List using Phone Number of Contact Android Studio

I am making a little app that has to do with phone numbers.

My question is I have a phone number that is in my Contact List in my phone. Example: 0877777777

I would like to open that Contacts information using that phone number.

Just to clarify the when I say contact list I mean the Contacts saved on my Phone.

If anyone could help me out I would appreciate it.

Upvotes: 4

Views: 2608

Answers (1)

marmor
marmor

Reputation: 28199

The PhoneLookup api is meant just for this.

String number = "0877777777";
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] projection = new String[]{ PhoneLookup._ID, PhoneLookup.DISPLAY_NAME };

Cursor cur = getContentresolver().query(uri, projection, null, null, null);

if (cur != null) {
   while (cur.moveToNext()) {
      Long id = cur.getLong(0);
      String name = cur.getString(1);
      Log.d("My Contacts", "found: " + id + " - " + name);
   }
   cur.close();
}

UPDATE

To open the contact's profile in the stock contacts app, you need to first get the contact's CONTACT_ID, and then use it in an Intent to the external app:

String number = "0877777777";
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] projection = new String[]{ PhoneLookup._ID };

Cursor cur = getContentresolver().query(uri, projection, null, null, null);

// if other contacts have that phone as well, we simply take the first contact found.
if (cur != null && cur.moveToNext()) {
    Long id = cur.getLong(0);

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, String.valueOf(id));
    intent.setData(contactUri);
    context.startActivity(intent);

    cur.close();
}

Upvotes: 3

Related Questions