Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch. Required: Array<Uri>! Found: Array<Uri?>

The ? and !! syntax is very confusing in kotlin! I'm declaring a value callback as a private member of my activity:

private lateinit var mFilePathCallback: ValueCallback<Array<Uri>>

And I assign it on onShowFileChooser on onCreate method like so:

    override fun onShowFileChooser(
    webView: WebView?,
    filePathCallback: ValueCallback<Array<Uri>>?,
    fileChooserParams: FileChooserParams?
): Boolean {
    mFilePathCallback = filePathCallback!! //Assigned here
    val intent = Intent(Intent.ACTION_GET_CONTENT)
    intent.type = "image/*"
    val PICKFILE_REQUEST_CODE = 100
    startActivityForResult(intent, PICKFILE_REQUEST_CODE)
    return true
}

But when I try to use it in onActivityResult like this:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if(data != null && resultCode == Activity.RESULT_OK) {
        val resultsArray = arrayOfNulls<Uri>(1)
        resultsArray[0] = data.data
        mFilePathCallback.onReceiveValue(resultsArray)
        Log.d("ACTIVITY RESULT", data.data.toString())
    } else {
        Log.d("ACTIVITY RESULT", "Cannot get file path.")
    }
}

I get the following error in onRecieveValue function call: Type mismatch. Required: Array<Uri>! Found: Array<Uri?> This is so confusing!

like image 491
Amol Borkar Avatar asked Mar 06 '26 17:03

Amol Borkar


2 Answers

All I had to do is cast results arrays as Array<Uri>:

mFilePathCallback.onReceiveValue(resultsArray as Array<Uri>)

like image 199
Amol Borkar Avatar answered Mar 09 '26 07:03

Amol Borkar


  1. arrayOfNulls<Uri>(1) returns Array<Uri?> because its elements can be null and are null to start with.

  2. Setting an element with resultsArray[0] = data.data doesn't change the type (why would it?).

  3. So you are passing an Array<Uri?> to mFilePathCallback.onReceiveValue which expects an Array<Uri> (an array whose elements are all Uri which can't be null).

Instead of the cast as in your own answer, just create the array of the correct type to start with:

val uri = data.data
if (uri != null) {
    val resultsArray = arrayOf<Uri>(uri)
    mFilePathCallback.onReceiveValue(resultsArray)
    Log.d("ACTIVITY RESULT", uri.toString()) // why toString?
} else {
    // your original code doesn't cover this case
    // so decide what to do here
}

Note that if you just do

val resultsArray = arrayOf<Uri>(data.data)

you should ideally get a warning because data.data can be null, but it doesn't seem to be properly marked as @Nullable.

like image 21
Alexey Romanov Avatar answered Mar 09 '26 06:03

Alexey Romanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!