pranay
pranay

Reputation: 2369

using the contacts manager in android

i have an app which shows the received messages as a Toast through a BroadcastReceiver. I am presently using the SmsMessage.getOriginatingAddress() method which gives me the number of the sender, how can modify it to get the corresponding name of the sender if stored in the contacts?

Upvotes: 0

Views: 518

Answers (1)

Robby Pond
Robby Pond

Reputation: 73484

You will need to query the contacts for the rest of the data.

First query for the contacts id using the phone number.

Cursor cursor = context.getContentResolver().query(
    Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, address),
    new String[] { Contacts.Phones.PERSON_ID }, null, null, null);

if (cursor != null) {
  try {
    if (cursor.getCount() > 0) {
      cursor.moveToFirst();
      Long id = Long.valueOf(cursor.getLong(0));
      if (Log.DEBUG) Log.v("Found person: " + id);
      return (String.valueOf(id));
    }
  } finally {
    cursor.close();
  }
}

Then query for the Contacts name with the id from the first query.

    Cursor cursor = context.getContentResolver().query(
    Uri.withAppendedPath(Contacts.People.CONTENT_URI, id),
    new String[] { PeopleColumns.DISPLAY_NAME }, null, null, null);
if (cursor != null) {
  try {
    if (cursor.getCount() > 0) {
      cursor.moveToFirst();
      String name = cursor.getString(0);
      if (Log.DEBUG) Log.v("Contact Display Name: " + name);
      return name;
    }
  } finally {
    cursor.close();
  }
}

You may be able to combine these two queries somehow.

Upvotes: 1

Related Questions