How to read a file using rememberLauncherForActivityResult in Kotlin Jetpack Compose?

So I have this composable which tries to read data from storage,

@Composable
private fun Screen() {
    val launcher = rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()) { result ->
        val uri = result.data?.data.toString()
        if(uri !== null) {
            val file = File(uri)
            val bytes = file.readBytes()
            println(bytes)
        }
    }
    Column() {
        Button(onClick = {
            val intent = Intent().setType("*/*").setAction(Intent.ACTION_OPEN_DOCUMENT)
            launcher.launch(intent)
        }) {
            Text("Open file")
        }
    }
}

However, it gives me this error: content:/com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2FIMG_CEFEFF486A8C-1.jpeg: open failed: ENOENT (No such file or directory). What am I doing wrong here? Please help.

Leave a Comment