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?

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
  }
}
2 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.