I’m trying t read ALL the numbers of my favorite contacts as below:
I’ve 3 favorite contacts, each one with 2 numbers, so I need to read the 6 numbers, my code is:
import android.annotation.SuppressLint
import android.content.Context
import android.provider.ContactsContract
import android.provider.ContactsContract.Contacts.CONTENT_URI
import android.provider.ContactsContract.Contacts.HAS_PHONE_NUMBER
import android.util.Log
import android.view.View
import android.provider.ContactsContract.CommonDataKinds.Phone as Phone
@SuppressLint("MissingPermission")
fun getFavoriteContacts(context: Context, layout: View): MutableList<String> {
var starredNumbers = mutableListOf<String>()
val TAG = "Contacts";
Log.i(TAG, "TAG: I'm here now")
Log.i(TAG, "TAG: I'm here now to read contacts")
val selection = ContactsContract.Contacts.STARRED + "='1'"
val phoneContactID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"
val cursor = context.contentResolver.query(CONTENT_URI,
null, selection, null, null)
if (cursor.count == 0){Log.i(TAG, "TAG: I'm here now ZERO contacts fond")}
while (cursor.moveToNext()) {
Log.i(TAG, "TAG: I'm here now for the contacts")
val phoneNumber = cursor.getString(
cursor.getColumnIndex(Phone.NUMBER))
starredNumbers.add(phoneNumber)
val hasPhoneNumber = Integer.parseInt(
cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)))
if (hasPhoneNumber > 0) {
//This is to read multiple phone numbers associated with the same contact
val contactId = mutableListOf<String>()
val phoneCursor = context.contentResolver.query(Phone.CONTENT_URI,
null, phoneContactID, contactId.toTypedArray(), null)
while (phoneCursor.moveToNext()) {
val phoneNumber = phoneCursor.getString(
phoneCursor.getColumnIndex(Phone.NUMBER))
Log.i(TAG, "Number read $phoneNumber");
starredNumbers.add(phoneNumber)
}
phoneCursor.close()
}
}
cursor.close()
return starredNumbers
}
But I’m getting this error: