我曾尝试使用WebView上传一个单一的文件,效果很好,但一旦我选择超过1个文件并上传,程序就会崩溃。但是,一旦我选择了1个以上的文件并上传,程序就崩溃了。代码如下。
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
}
}
这是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
}
从logcat中,我可以看到崩溃点是: results![i] = item.uri 当我在OnActivityResult中的For循环中从clipData中获取uri时。我对那行代码做了注释。崩溃信息是"kotlin.KotlinNullPointerException".
我找到了解决方案。
只是需要初始化结果。
results= Array(clipData.itemCount, {clipData.getItemAt(0).uri})