tags:

views:

45

answers:

1

hi, 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?

+1  A: 

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.

BrennaSoft
thanks a lot :)
pranay
when i am using Contacts.Phones then i get a warning that the type is depreciated so which other type should i use?will the following method give the desired resultL?Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber)); resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME},null,null,null);
pranay
i tried this: Cursor cursor = context.getContentResolver().query(Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, address), new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null); but on running the app i get a Null Pointer Exception in this line
pranay
also shouldn't there be a catch statement here?
pranay
finally solved it thanks:)
pranay