From 4b16fde9195df91cf9633540d4ba4fe4beec00fc Mon Sep 17 00:00:00 2001 From: tibbi Date: Fri, 3 Apr 2020 21:04:02 +0200 Subject: [PATCH] improving the way contact name is fetched from number, handle some new cases --- .../smsmessenger/extensions/Context.kt | 36 +++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/app/src/main/kotlin/com/simplemobiletools/smsmessenger/extensions/Context.kt b/app/src/main/kotlin/com/simplemobiletools/smsmessenger/extensions/Context.kt index 323d4897..9091196d 100644 --- a/app/src/main/kotlin/com/simplemobiletools/smsmessenger/extensions/Context.kt +++ b/app/src/main/kotlin/com/simplemobiletools/smsmessenger/extensions/Context.kt @@ -55,8 +55,16 @@ fun Context.getMessages(threadID: Int? = null): ArrayList { val read = cursor.getIntValue(Telephony.Sms.READ) == 1 val person = cursor.getIntValue(Telephony.Sms.PERSON) val thread = cursor.getIntValue(Telephony.Sms.THREAD_ID) - if (address != null && person != 0 && hasContactsPermission) { - address = getPersonsName(person) ?: address + + if (hasContactsPermission) { + if (address != null && person != 0) { + address = getPersonsName(person) ?: address + } else if (address.areDigitsOnly()) { + val contactId = getNameFromPhoneNumber(address) + if (contactId != null) { + address = getPersonsName(contactId) ?: address + } + } } val message = Message(id, subject, body, type, address, date, read, thread) @@ -125,3 +133,27 @@ fun Context.getPersonsName(id: Int): String? { return null } + +fun Context.getNameFromPhoneNumber(number: String): Int? { + val uri = CommonDataKinds.Phone.CONTENT_URI + val projection = arrayOf( + ContactsContract.Data.CONTACT_ID + ) + + val selection = "${CommonDataKinds.Phone.NUMBER} = ? OR ${CommonDataKinds.Phone.NORMALIZED_NUMBER} = ?" + val selectionArgs = arrayOf(number, number) + + var cursor: Cursor? = null + try { + cursor = contentResolver.query(uri, projection, selection, selectionArgs, null) + if (cursor?.moveToFirst() == true) { + return cursor.getIntValue(ContactsContract.Data.CONTACT_ID) + } + } catch (e: Exception) { + showErrorToast(e) + } finally { + cursor?.close() + } + + return null +}