Reputation: 161
I have implemented the selection of contacts from the phone book in my application. In order for the intent with action PICK to work on android 11, I added this to my manifest:
<queries>
<intent>
<action android:name="android.intent.action.PICK" />
<data android:mimeType="vnd.android.cursor.dir/phone_v2" />
</intent>
</queries>
The code works fine on android versions 10 and below. But on android version 11, the contact I selected from the phone book is not inserted into the text field of my application, because ContentResolver.query return empty cursor. it.moveToFirst() returns false Here is my code:
Constants.START_PICK_CONTACT_ACTION -> {
data?.data?.let { uri ->
activity.contentResolver.query(uri, null, null, null, null)?.use {
if (it.moveToFirst()) {
val number: String? = it.getString(it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
etPhoneNumber.setText(number)
}
}
}
}
Please, help me.
Upvotes: 5
Views: 2509
Reputation: 31
I encountered the same issue. After trying many times, I found that:
a) Please double check if you have declared READ_CONTACTS
permission in AndroidManifest.xml
. If yes, we need to gain the runtime permission for READ_CONTACTS
. Otherwise the ContentResolver.query() just return an empty cursor.
AndroidManifest.xml looks like:
<manifest>
...
<uses-permission android:name="android.permission.READ_CONTACTS" />
...
<queries>
<intent>
<action android:name="android.intent.action.PICK" />
<data android:mimeType="vnd.android.cursor.dir/phone_v2" />
</intent>
</queries>
</manifest>
Code snippet:
activity?.let {
if (ContextCompat.checkSelfPermission(it, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
//openContact()
} else {
requestPermissions(
arrayOf(Manifest.permission.READ_CONTACTS),
REQUEST_PERMISSION_READ_CONTACT_CODE
)
}
}
...
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
// openContact()
}
b) If there is no declaration of READ_CONTACTS
permission in manifest, just add query element is enough.
AndroidManifest.xml looks like:
<manifest>
...
<uses-permission android:name="android.permission.READ_CONTACTS" />
...
<queries>
<intent>
<action android:name="android.intent.action.PICK" />
<data android:mimeType="vnd.android.cursor.dir/phone_v2" />
</intent>
</queries>
</manifest>
But I cannot find any documentation can explain this behavior, does anyone know the root cause? Would appreciate it very much if you could tell.
Upvotes: 1
Reputation: 61
I've had a similar issue. Need to grant android.Manifest.permission.READ_CONTACTS
permission before trying to call query
Upvotes: 6