これは、カーソルから連絡先情報を取得するのに役立つようにここに追加する (Kotlin での) 実装があると便利です。また、アクセス許可を付与し、実行時のアクセス許可を要求する必要があります
<uses-permission android:name="android.permission.READ_CONTACTS" />
@SuppressLint("Recycle")
private fun getContactDataFrom(
contentResolver: ContentResolver,
contactUri: Uri
): ContactModel? {
val projection = arrayOf(
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER
)
try {
val cursor = contentResolver.query(contactUri, projection, null, null, null) ?: return null
if (!cursor.moveToFirst()) {
return null
}
val id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))
val name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
val hasNumber = (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)))
cursor.close()
val email = getEmail(contentResolver, id)
val phoneNumber = if (hasNumber > 0) {
getPhoneNumber(contentResolver, id)
} else {
""
}
return ContactModel(name, phoneNumber, email)
} catch (e: Exception) {
Log.e("Contacts", "Could not get contact info.", e)
return null
}
}
@SuppressLint("Recycle")
private fun getPhoneNumber(contentResolver: ContentResolver, id: String?): String {
var phoneNumber = ""
val cursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.Contacts._ID + " = ?",
arrayOf(id),
null
) ?: return phoneNumber
if (cursor.moveToFirst()) {
phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA))
}
cursor.close()
return phoneNumber
}
@SuppressLint("Recycle")
private fun getEmail(contentResolver: ContentResolver, id: String?): String {
var email = ""
val cursor = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
arrayOf(id),
null
) ?: return email
if (cursor.moveToFirst()) {
email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA))
}
cursor.close()
return email
}
引き金:
val intent = Intent(this, PickLabelActivity::class.java)
startActivityForResult(intent, PickLabelActivity.REQ_CODE_PICK_LABEL)
onActivityResult での使用法は次のようになります。
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && requestCode == ConstantsHandler.INTENT_CODE_PICK_CONTACT) {
val contactUri = data?.data ?: return
val contactModel = getContactDataFrom(contentResolver, contactUri)
inputName.setText(contactModel?.name)
inputPhone.setText(contactModel?.phone)
inputEmail.setText(contactModel?.email)
}
}
その ContactModel は単純なデータ クラスです。
data class ContactModel(
var name: String? = null,
var phone: String? = null,
var email: String? = null
) : Serializable