Search code examples
androidsmsinbox

How to read sms sender's name?


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?


Solution

  • 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();