filepath不断返回null

enyaitl3  于 2021-07-09  发布在  Java
关注(0)|答案(0)|浏览(168)

我一直在尝试使用kotlin在我的应用程序中实现一个功能,允许用户在单击空图像槽后上载图像:

override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.get_started)
    val imageView = findViewById<View>(R.id.userPhoto) as ImageView

    imageView.setOnClickListener{
        selectImage()
    }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == RESULT_OK) {
        Log.d("demo", "data: " + data!!.data)
        val bitmap = getPath(data!!.data)
        Log.d("demo", "passed this point 4")
        imageView!!.setImageBitmap(bitmap)
    }

}

private fun getPath(uri: Uri?): Bitmap {
    val projection = arrayOf(MediaStore.Images.Media._ID)

    Log.d("demo", "projection: " + projection.contentDeepToString())

    val cursor = contentResolver.query(uri!!, projection, null, null, null)
    val columnIndex = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media._ID)

    Log.d("demo", "columnIndex: $columnIndex")
    Log.d("demo", "cursor: $cursor")

    cursor.moveToFirst()

    Log.d("demo", "cursor: $cursor")

    val filePath = cursor.getString(columnIndex)
    // cursor.close()

    Log.d("demo", "filepath: $filePath")
    // Convert file path into bitmap image using below line.
    return BitmapFactory.decodeFile(filePath)
}

private fun selectImage() {
    val intent = Intent()
    intent.type = "image/*"
    intent.action = Intent.ACTION_GET_CONTENT
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE)
    }

一切似乎都很正常,除了在getpath()函数中,当我从android库中选择一个图像时,我总是得到空值。有人知道是什么引起的吗?java版本的代码是从这里得到的
编辑:原来问题出在 BitmapFactory.decodeFile(filePath) 一直返回null的行
edit2:我可以通过去掉 getPath() 并使用以下代码 onActivityResult() :

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            Log.d("demo", "passed this point 3")
            Log.d("demo", "data: " + data!!.data)
            val `is` = contentResolver.openInputStream(data!!.data!!)
            val bitmap = BitmapFactory.decodeStream(`is`)
            Log.d("demo", "passed this point 4")
            imageView?.setImageBitmap(bitmap)
            imageView?.bringToFront()
        }

    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题