Skip to content

Commit d6f5bca

Browse files
committed
CallLogAdapter.kt: Improve contact name retrieval and error handling
1 parent 93d8bbb commit d6f5bca

File tree

1 file changed

+24
-15
lines changed

1 file changed

+24
-15
lines changed

app/src/main/java/com/addev/listaspam/adapter/CallLogAdapter.kt

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import android.content.pm.PackageManager
99
import android.net.Uri
1010
import android.provider.CallLog
1111
import android.provider.ContactsContract
12+
import android.util.Log
1213
import android.view.Gravity
1314
import android.view.LayoutInflater
1415
import android.view.View
@@ -83,7 +84,12 @@ class CallLogAdapter(
8384
val number = callLog.number ?: "Unknown number"
8485
val contactName = getContactName(context, number)
8586
val textToShow = if (isBlocked) {
86-
context.getString(R.string.blocked_text_format, contactName ?: number)
87+
val displayText = when {
88+
contactName != null -> contactName
89+
number.isNotBlank() -> number
90+
else -> context.getString(R.string.unknown_value)
91+
}
92+
context.getString(R.string.blocked_text_format, displayText)
8793
} else if (isWhitelisted) {
8894
context.getString(R.string.whitelisted_text_format, contactName ?: number)
8995
} else {
@@ -234,25 +240,28 @@ class CallLogAdapter(
234240
}
235241

236242
private fun getContactName(context: Context, phoneNumber: String): String? {
237-
if (ContextCompat.checkSelfPermission(
238-
context,
239-
Manifest.permission.READ_CONTACTS
240-
) == PackageManager.PERMISSION_GRANTED
241-
) {
242-
val contentResolver = context.contentResolver
243-
val uri =
244-
ContactsContract.PhoneLookup.CONTENT_FILTER_URI.buildUpon().appendPath(phoneNumber)
245-
.build()
243+
if (phoneNumber.isBlank()) return null
244+
245+
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
246+
!= PackageManager.PERMISSION_GRANTED
247+
) return null
248+
249+
return try {
250+
val uri = Uri.withAppendedPath(
251+
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
252+
Uri.encode(phoneNumber)
253+
)
246254
val projection = arrayOf(ContactsContract.PhoneLookup.DISPLAY_NAME)
247255

248-
contentResolver.query(uri, projection, null, null, null)?.use { cursor ->
256+
context.contentResolver.query(uri, projection, null, null, null)?.use { cursor ->
249257
if (cursor.moveToFirst()) {
250-
return cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME))
251-
}
258+
cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME))
259+
} else null
252260
}
261+
} catch (e: Exception) {
262+
Log.e("getContactName", "Lookup failed for $phoneNumber", e)
263+
null
253264
}
254-
255-
return null
256265
}
257266

258267
private fun clipboardAction(number: String) {

0 commit comments

Comments
 (0)