I\'m making an text message application and want to access contacts in my Android application .
I want to access contacts as if they where in the actual contact list. W
I was able to use @Balaji.K 's example with some modification. The main issue I ran into is that
while (cursor.moveToNext()) {
will skip over the first result.
I also wanted to build a list of phone numbers for a user to select from if none are marked as "Mobile". I also pass in a name to search (variable replaced with in this example), but one could modify this code to build a collection by replacing "selection" and "selection_args" with null and iterating over everything in "contacts" as I did for "phones". Here is what I ended up with (in Kotlin):
val selection = "lower(${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY}) LIKE ?"
val selectionArgs = arrayOf("")
selectionArgs[0] = "%%"
// Query contacts for someone with a matching name
val contacts = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,
null, selection, selectionArgs, null)
contacts!!.moveToFirst()
if (contacts.count > 1) {
// TODO: Disambiguate and move to the correct position
}
val contactId = contacts.getString(contacts.getColumnIndex(
ContactsContract.Contacts._ID))
// Check if contact has at least one phone number
if (contacts.getString(contacts.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER)) == "1") {
val sel = "${ContactsContract.CommonDataKinds.Email.CONTACT_ID} = ?"
val selArgs = arrayOf(name)
val sort = "${ContactsContract.CommonDataKinds.Email.LAST_TIME_CONTACTED} DESC"
selArgs[0] = contactId
val phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, sel, selArgs, sort)
phones!!.moveToFirst()
// Iterate through phone numbers if multiple
if (phones.count > 1) {
val phoneNumbers = mutableMapOf()
var loop = true
var mobileIndex: Int? = null
while (loop) {
val phoneType = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))
val phoneName = ContactsContract.CommonDataKinds.Phone.getTypeLabel(resources, phoneType, null).toString()
phoneNumbers[phones.position] = ContactData(phoneName, phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)))
// Remember what position the mobile number was in
if (phoneType == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
mobileIndex = phones.position
}
loop = phones.moveToNext()
}
phones.moveToPosition(mobileIndex)
}
}