Search code examples
androidsmsandroid-contentprovider

How to read "Contact Name" from inbox messages


I'm reading sms messages from inbox using content provider. See following code:

Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = this.getContentResolver().query(uriSms, null, null, null, SORT_ORDER);

Inside loop I'm fetching all required columns:

String body= cursor.getString(cursor.getColumnIndex("body"));
String person = cursor.getString(cursor.getColumnIndex("person"));

I'm getting all values properly but person's name is returning 'null' value. Please guide me why contact name is not being returned from above statement.


Solution

  • The person column's value, if it exists, is not the sender's name. It's an ID that you would use to query the Contacts Provider to get the name. If you're getting null for person, then you'll have to use the address, which is the phone number, to query against. For example:

    String address = cursor.getString(cursor.getColumnIndex("address"));
    
    final String[] projection = new String[] {ContactsContract.Data.DISPLAY_NAME};
    
    String displayName = null;
    Cursor contactCursor = null;
    
    try {
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                                       Uri.encode(address));
    
        contactCursor = getContentResolver().query(uri,
                                                   projection,
                                                   null,
                                                   null,
                                                   null);
    
        if (contactCursor != null && contactCursor.moveToFirst()) {
                displayName = contactCursor.getString(
                    contactCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
        }
    }
    catch(Exception e) {
        e.printStackTrace();
    }
    finally {
        if(contactCursor != null) {
            contactCursor.close();
        }
    }