Android Kotlin-取消图库选择后,应用程序停止运行

时间:2018-09-05 18:12:59

标签: java android kotlin

这是代码:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_upload_image)

        but.setOnClickListener {
            chooseImage()
        }

    }

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

public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
    if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
        // do stuff
    }else{
        Toast.makeText(this, "CANCELLED", Toast.LENGTH_LONG).show()
    }
}

我从app crashes when going back from gallery without selecting any image处获得了requestCode == 1 && resultCode == RESULT_OK && data != null,因为存在相同的问题,但是我无法使用此解决方案,当我在手机上点按后退按钮而不选择时,应用程序崩溃图片。我想念什么吗?

1 个答案:

答案 0 :(得分:3)

取消操作后,data将为null(由图库应用返回),但Kotlin默认情况下不允许null,因此出现了问题。

为避免这种情况,请将data设置为?设为Intent?

public override fun onActivityResult(requestCode: Int,
               resultCode: Int,
               data: Intent?) {
// mark as null type       ^