Primarily, I want to clarify that this isn't a duplicate. I've gone through every question on Stack Overflow that has a similar topic but couldn't find a solution. I've also gone through the documentation, which doesn't specifically mention this issue.
I'm trying to convert a Uri to a File using .toFile()
in Kotlin; however, it throws an error that says:
java.lang.IllegalArgumentException: Uri lacks 'file' scheme: content://com.android.externalstorage.documents/document/primary%3Asample.txt
at androidx.core.net.UriKt.toFile(Uri.kt:43)
I've accessed the file through the file picker, and I've also requested READ_EXTERNAL_STORAGE
. Although the file can be picked, it throws the error I mentioned above. The code for accessing the file looks like this:
val activityResultLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
val file = uri?.toFile()
if (file != null) {
Log.d("data file", file.readText())
}
}
How can I fix this?
Thank you.
Well, if anyone is still stuck with the same problem, you can try this code:
val activityResultLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
val file = createTempFile()
uri?.let { context.contentResolver.openInputStream(it) }.use { input ->
file.outputStream().use { output ->
input?.copyTo(output)
}
}
Log.d("txt content", file.readText())
file.delete()
}
For more context: https://stackoverflow.com/a/49221353/22091687