I'm trying to get some information about a contact that the user can select in the contact list, using Kotlin. I tried a couple tutorials that only worked partly. This is the code that should call startActivityForResult(), from MainActivity.kt
:
add_contact.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
startActivityForResult(intent, CONTACT_PICK_CODE)
}
And the following is the overridden onActivityResult
method:
@SuppressLint("Range")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// handle intent results || calls when user from Intent (Contact Pick) picks or cancels pick contact
if (resultCode == RESULT_OK) {
if (requestCode == CONTACT_PICK_CODE) {
val cursor1: Cursor
val cursor2: Cursor?
// get data from intent
val uri = data!!.data
cursor1 = contentResolver.query(uri!!, null, null, null, null)!!
if (cursor1.moveToFirst()) {
// get contact details
val contactId = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts._ID))
val contactName = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
val contactThumbnail = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI))
val idResults = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))
val idResultHold = idResults.toInt()
// check if contact has a phone number or not
if (idResultHold == 1) {
cursor2 = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
null,
null
)
// a contact may have multiple phone numbers
var contactNumber : String = ""
while (cursor2!!.moveToNext()) {
// get phone number
contactNumber = cursor2.getString(cursor2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
}
Toast.makeText(this, "Contact number: $contactNumber", Toast.LENGTH_SHORT).show()
cursor2.close()
}
cursor1.close()
}
}
} else {
Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show()
}
}
The line that prints "Contact number: ..." never prints the contact number, which means that the while
loop never runs.
All the other variables (contactId
, contactName
...) seem to be assigned the correct value every time, but the number doesn't. Does anyone know what causes that to happen?
from Getting contact information from contact list with Kotlin
No comments:
Post a Comment