简体   繁体   中英

How do you fix type mismatch error when picking contacts?

On this line in

val contactUri: Uri? = data.data
…
val cursor = requireActivity().contentResolver
    .query(**contactUri**, queryFields, null, null, null)

Type mismatch required Uri got Uri

How do you fix this?

Code sample

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    when {
        resultCode != Activity.RESULT_OK -> return

        requestCode == REQUEST_CONTACT && data != null -> {
            val contactUri: Uri? = data.data
            // Specify which fields query to return values for.
            val queryFields = arrayOf(ContactsContract.Contacts.DISPLAY_NAME)
            // Perform query
            val cursor = requireActivity().contentResolver
                .query(contactUri, queryFields, null, null, null)
            cursor?.use {
                // Double-check that you actually got results
                if (it.count == 0) {
                    return
                }

                // Pull out the first column of the first row of data
                it.moveToFirst()
                val suspect = it.getString(0)
                crime.suspect = suspect
                crimeDetailViewModel.saveCrime(crime)
                suspectButton.text = suspect
            }
        }
    }
}

Either try removing the ? after your uri so:

val contactUri: Uri = data.data

instead of

val contactUri: Uri? = data.data

Or if that doesn't work, check this answer out

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM