OnActivityResult Uri error

On this line:
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?

2 Likes

Looking at my solution, I modified the first line to be

val contactUri: Uri = data.data ?: return

If we do not have any data, then we cannot continue with the query so this helps protect our nullability. For greater scope, here is the larger function

when {
  resultCode != Activity.RESULT_OK -> return
  requestCode == REQUEST_CONTACT && data != null -> {
    val contactUri: Uri = data.data ?: return
    // the rest of the cursor & query calls
  }
  requestCode == REQUEST_PHOTO -> {
    // do photo stuff from Chapter 16
  }
}
6 Likes

Awesome that fixed it, thank you.

I used double exclamation to satisfy the IDE. Iā€™m not sure if this is much better that jpaone answer but it works fine for me.

 val cursor = contactURI?.let {
                    requireActivity().contentResolver
                        .query(it, queryFields, null, null, null)
                }
1 Like