So... Yesterday my code was working just fine, but today, I don't know what happend it stoped working. The cursor is null and returns both "". I don't know what to do.
Is the cursor even working?
@SuppressLint("Range", "Recycle")
@Composable
fun ContactPickerTwinTurbo(
done: (String, String) -> Unit
) {
val context = LocalContext.current
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickContact(),
onResult = {
val contentResolver: ContentResolver = context.contentResolver
var name = ""
var number = ""
val cursor: Cursor? = contentResolver.query(it!!, null, null, null, null)
if (cursor != null) {
if (cursor.moveToFirst()) {
name =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
Log.d("Name", name)
val id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))
val phones: Cursor? = contentResolver.query(
Phone.CONTENT_URI, null,
Phone.CONTACT_ID " = " id, null, null
)
if (phones != null) {
while (phones.moveToNext()) {
number = phones.getString(phones.getColumnIndex(Phone.NUMBER))
Log.d("Number", number)
}
phones.close()
}
}
}
done(name, number)
}
)
Button(
onClick = {
launcher.launch()
},
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
) {
Text(text = "Pick Contact")
}
}
How does the cursor works? Do I have to wait? am I supposed to ask permission to access the contacts?
CodePudding user response:
Apparently Yes you need to ask for permission in runtime to get access the contact. For References check this link [check link][1]https://www.geeksforgeeks.org/contact-picker-in-android-using-jetpack-compose/