用户未选择图像时出现错误如何解决

时间:2020-01-02 07:55:16

标签: android image validation kotlin uri

用户未选择“图像”如何在Kotlin中检查图像验证时出现错误

 fun getPath(uri: Uri): String? {

    var cursor = contentResolver.query(uri, null, null, null, null)

    if (cursor != null) {
        cursor!!.moveToFirst()
        var document_id = cursor.getString(0)
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1)
        cursor.close()
        cursor = contentResolver.query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null,
            MediaStore.Images.Media._ID + " = ? ",
            arrayOf(document_id),
            null
        )
    }


    cursor!!.moveToFirst()
        var path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
        cursor.close()
        if (path == null) {
            path = ""
        }
        return path
}

这是活动结果代码

 public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            val selectedImageUri = data!!.data
            selecteImageUri = Uri.parse(selectedImageUri.toString())
            if (selecteImageUri != null) {
                val filePath = getPath(selecteImageUri)
                binding.imageAddButton.text = filePath
            }

            else {
                AppLogger.toast("Please Select an Image")
            }
        }
    }
}

如果用户没有从图库中选择图像,这是我的意图函数

  R.id.imageAddButton -> {
            val intent = Intent()
            intent.type = "image/*"
            intent.action = Intent.ACTION_GET_CONTENT
            startActivityForResult(
                Intent.createChooser(
                    intent,
                    "Select Picture"
                ), SELECT_PICTURE
            )
        }

我总是在这里出错

 cursor!!.moveToFirst()

如何解决此问题,请提前帮助我,谢谢您,我会很感激每个答案

0 个答案:

没有答案