Load SMS conversation along with contact name

715 views Asked by At

I'm developing a SMS application and come to the following issue. Currently I can read SMS conversation by using provider Telephony.Sms.Conversations by using CursorLoader. From cursor returned by this CursorLoader, I can display conversations's address which are phone numbers.

My question is how to retrieve SMS conversation contact name efficiently to display along with SMS conversation, not the phone number. Is there anyway to load list of contacts from list of phone numbers returned by the CursorLoader before?. Of course I've tried to load one by one contact name by using phone number but that terribly reduce the application performance.

Thank you in advance.

1

There are 1 answers

0
Lampione On

I've been searching for a solution myself and eventually came out with a good compromise in my opinion.

As soon as my query is finished, I store in an HashMap<String, String> contact_map my values as

int SENDER_ADDRESS = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.ADDRESS);

while (cursor.moveToNext()) {
                contact_map.put(
                        cursor.getString(SENDER_ADDRESS),
                        getContactName(getApplicationContext(), cursor.getString(SENDER_ADDRESS))
                );
            }

Method getContactName:

public static String getContactName(Context context, String phoneNumber) {
    ContentResolver cr = context.getContentResolver();
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
    if (cursor == null) {
        return null;
    }
    String contactName = null;
    if(cursor.moveToFirst()) {
        contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
    }

    if(cursor != null && !cursor.isClosed()) {
        cursor.close();
    }

    if (contactName != null) {
        return contactName;
    } else {
        return phoneNumber;
    }

}

EDIT: I then get the contact name with

String name = contact_map.get(cursor.getString(SENDER_ADDRESS));

Hope it helps!