Calling getStringExtra("key") on my Intent gives me null

416 Views Asked by At

This is so simple but still doesn't work. I simply want to pass a string to the ACTION_PICK Intent to retrieve it in registerForActivityResult.

Here is my code:

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

        val gallery = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
        gallery.putExtra("filename", "test")
        resultLauncher.launch(gallery)
    }

    private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) { 
            
            val fileName: String = result.data?.getStringExtra("filename").toString() 

            Log.i("###", "Filename is $fileName")

        }
    }
}

First I'm creating the Intent and call .putExtra to pass a String, in registerForActivityResult I call result.data?.getStringExtra("filename").toString() but it prints out "Filename is Null".

What am I doing wrong?

1

There are 1 best solutions below

2
On

I simply want to pass a string to the ACTION_PICK Intent to retrieve it in registerForActivityResult

That is not supported, sorry. The Intent that you use to start the activity is not the same Intent that you receive in response. And, there is no requirement for extras on the first Intent to get copied into the second Intent.