As the title says, I want to select contacts list from the phone contacts which start from the given alphabet. for example: if i want to select only the contacts starting with A, my current code which i tried is:
val selecteContactsList: ArrayList<SelectedContactItem> = arrayListOf()
val cursor = context.contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
arrayOf(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
),
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ?",
arrayOf("A"),
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
)
while (cursor!!.moveToNext()) {
val contactName =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
val contactNumber =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
val contactItem = SelectedContactItem(contactNumber, contactName)
selecteContactsList.add(contactItem)
}
cursor.close()
But this does not give any output. total selected contacts count is 0. Any help would be appreciated. Thanks in advance.
the part:
Phone.DISPLAY_NAME + " = ?",
arrayOf("A"),
means 'return all contacts with name A'.
I think you want to ask 'return all contacts with name starting with the letter A' which is a different query.
To do that you can change the code to:
Phone.DISPLAY_NAME + " LIKE 'A%'"
If you want a case insensitive query (i.e. include names that begin with small 'a'), try:
Phone.DISPLAY_NAME + " LIKE 'A%' COLLATE NOCASE"
However, if your goal is to show a list of all contacts, and have a scroller sidebar where the user can touch the letter "C" and jump to contact names beginning with that letter I would not suggest to have such queries, instead query for all contacts on the device, and show them all in one big scrollable list, and have those letters buttons scroll to a certain position in the list when touched.
The user experience would be far superior.