Hello, i have an query regarding registForActivity...
# android
d
Hello, i have an query regarding registForActivityResult, when to get the URI for the file selected
Copy code
val registerTakeFile = registerForActivityResult(
    ActivityResultContracts.OpenDocument()
) { uri ->
    File(uri.path)
    if (uri != null) {
        var file = File(uri.path!!).name
        fileNames.value = file
    } else {
        fileNames.value = ""
    }
}
The path that i'm getting is something like
/document/msf:27
how to i get the real path from the URI, is there something that i'm missing here
i
You do not get access to the file at all, just the Uri. Use the
ContentResolver
methods like
openInputStream
to access the file contents from the Uri
👍 1
d
I was using it in Composable Method. How do i get the ContentResolver instance in a composable function
i
LocalContext.current.contentResolver
e
add Intent.CATEGORY_OPENABLE to request only URIs that can be read with ContentResolver.openFileDescriptor() and support ContentResolver.query(arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)) to retrieve more info
i
Note that
ActivityResultContracts.GetContent
and
GetMultipleContents
already add
CATEGORY_OPENABLE
for you, as per the docs
d
@Ian Lake I was able to get the size of the file, But how do i get the path and other details of the file
Copy code
val registerTakeFile = registerForActivityResult(
    ActivityResultContracts.OpenDocument()
) { uri ->
    File(uri.path)
    if (uri != null) {
        var inputStream: InputStream? = null
        val fileReader = ByteArray(4096)
        var fileSizeDownloaded: Long = 0
        inputStream = context.contentResolver.openInputStream(uri)
        while (true) {
            val read = inputStream!!.read(fileReader)
            if (read == -1) {
                break
            }
            fileSizeDownloaded += read
        }
     }
}
i
There is no path; there is no access to the file
The Uri could be pointing to a file on a cloud server or Google Drive
d
So if i want to get the Path of a file in the device storage, there is no way to that.
i
You don't have access to the file even if you did have a path
Particularly on later versions of Android
d
okay
I guess then i need to file a way around in building this functionality. I have to send the file, path and some other details for any particular file that user selects from the device FileExplorer to an post api
because i remember we were able to do this before the changes in the storage access framework.
i
Using a
File
has always been the wrong abstraction for any library.
InputStream
or
FileDescriptor
was what any library should have used as input
d
Okay thank your help. 🙏