SuperBerry
SuperBerry

Reputation: 1293

How to upload multiple files in WebView on Android in Kotlin?

I have tried to use the WebView to upload one single file and it works well. However, once I selected more than 1 file and upload, the program crashed. The code is below:

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

    if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage || requestCode != FILECHOOSER_RESULTCODE) return

        var results: Array<Uri>? = null

        if (resultCode === Activity.RESULT_OK) {
            if (intent != null) {
                val dataString = intent.dataString
                val clipData = intent.clipData
                if (clipData != null) {


                    for (i in 0 until clipData.itemCount) {
                        val item = clipData.getItemAt(i)
                        results!![i] = item.uri //Here is the crash point
                    }
                }

                if (dataString != null) results =
                    arrayOf(Uri.parse(dataString))
            }
        }


        mUploadMessage!!.onReceiveValue(results)
        mUploadMessage = null



        return


    }
}

And here is the code in WebChromeClient():

override fun onShowFileChooser(
            view: WebView,
            filePathCallback: ValueCallback<Array<Uri>>,
            fileChooserParams: FileChooserParams
        ): Boolean {

            if (mUploadMessage!= null) {
                mUploadMessage!!.onReceiveValue(null);
                mUploadMessage = null;
            }

            mUploadMessage = filePathCallback
            val intent = fileChooserParams.createIntent()

            intent.addCategory(Intent.CATEGORY_OPENABLE)

            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
            intent.setType("*/*")

            startActivityForResult(intent, FILECHOOSER_RESULTCODE)
            return true







        }

From the logcat I can see the crash point is results!![i] = item.uri when I get the uri from clipData in the For loop in OnActivityResult. I have comment on that code line. The crash message is "kotlin.KotlinNullPointerException".

Upvotes: 0

Views: 1307

Answers (1)

SuperBerry
SuperBerry

Reputation: 1293

I found the solution.

Just need to initialize the results:

results= Array(clipData.itemCount, {clipData.getItemAt(0).uri})

Upvotes: 1

Related Questions