0

I use Uri.parse("content://sms/inbox") to read SMSs, but I can't figure how to read the sender's name. I went through similar questions but couldn't find clear answers, only suggestions to use:

ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null,null, null);
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

Which give me the name of my contacts but not the specific name for every SMS.

By the way, when I use "body", it show me all of my SMS's history. Is there a way to check like:

messageString = cursor.getString(0); //let's say 0 is "body"
(messageString == "HI") txt.setText("BYE");

and not just get the full inbox content?

user3395989
  • 73
  • 1
  • 12
  • you need get Address of SMS then check in your contact with that address, Display name could be null in some phone, and for checking String use `.equals()` instead of `==` – Shayan Pourvatan Aug 02 '14 at 19:35

1 Answers1

1

first get the sender phone number then compare sender number with number in the contact list somthing like this :

Cursor phones = getContentResolver().query(ContactsContract.
CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.
CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.
CommonDataKinds.Phone.NUMBER));
  if (phoneNumber.equals(senderphonenumber)){
      //do something
   }
   }
  phones.close();
Meysam
  • 694
  • 6
  • 20
  • Okay, last question, after I check if the phoneNumber and the senderphonenumber are the same, how do I enter the part that tell me the name of the sender? Change the phoneNumber to DISPLAY_NAME? – user3395989 Aug 03 '14 at 18:09
  • its simple, in the above code you see String name its return name off contact ! look the code and choose the best answer if its useful. – Meysam Aug 03 '14 at 18:37
  • To compare phone numbers you should use PhoneNumberUtils.compare(). It takes into account are codes and such so that you can match numbers that are not written in exactly same format, but are still the same number. – Janne Oksanen Sep 27 '16 at 11:19