Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsafe use of a nullable receiver type Bundle? android app will compile with warning but instantly crashes

I am new to kotlin and android programming, and it seems like this language is moving rather quick without some backwads capabilities.

Here are my two main functions in MainActivity.kt

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

    cameraButton.setOnClickListener {
        val callCameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if(callCameraIntent.resolveActivity(packageManager) != null) {
            startActivityForResult(callCameraIntent, CAMERA_REQUEST_CODE)
        }
    }

    replaceFragment(ReportsFragment())
    bottom_navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)


}

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

    val dt: Intent? = data

    when(requestCode) {
        CAMERA_REQUEST_CODE -> {
            if(resultCode == Activity.RESULT_OK && data != null) {
            //if(data != null) {
                //&& data != null){
                photoImageView.setImageBitmap(data.extras.get("data") as Bitmap)
            }
        }
        else -> {
            Toast.makeText(this, "Unrecognized request code", Toast.LENGTH_SHORT).show()
        }
    }
}

The error seems to come in the "WHEN" block of onActivityResult.

I have wrapped the data (Intent being passed) in null checks, tried to declare it as a new value with a null check, but it constantly gets the same warning when compiling:

Unsafe use of a nullable receiver of type Bundle?

It also keeps saying this depreciated warning: Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.

I have switched the gradle version to 5.1.1 and have the android Gradle plugin currently at 3.4.0 (could either of these be part of my issue)

like image 431
pquery Avatar asked May 14 '19 10:05

pquery


1 Answers

The data.extras might be null, therefore make sure to use it with ?. and as?:

photoImageView.setImageBitmap(data?.extras?.get("data") as? Bitmap)

All three make sure that if data, data.extras or "data" are null or not a Bitmap, the chain itself is null.

The deprecated Gradle features are usually warnings about deprecated APIs. Just make sure to update all your plugins to the newest ones and don't update to Gradle 6 as long as you require plugins which don't adapt to the new API. But for now it's only warning you about relevant changes.

like image 94
tynn Avatar answered Oct 21 '22 11:10

tynn