Can't get file uri from intent onActivityResult
Solution 1:
I would like to receive normal file path from onActivityResult like this:
My guess is that you are using ACTION_OPEN_DOCUMENT
, or perhaps ACTION_GET_CONTENT
. You are getting a content
Uri
, which is exactly what those Intent
actions are documented to return. Such a Uri
might be backed by:
- A local file on external storage, which you probably cannot access on Android 10+
- A local file on internal storage for the other app
- A local file on removable storage
- A local file that is encrypted and needs to be decrypted on the fly
- A stream of bytes held in a
BLOB
column in a database - A piece of content on the Internet that needs to be downloaded by the other app first
- Content that is generated on the fly
- ...and so on
this exception comes from method which converts my file to string
I assume that by "converts my file to string", you mean read the file contents in as a String
. In that case:
- Get a
ContentResolver
by callinggetContentResolver()
on aContext
, such as yourActivity
- Call
openInputStream()
on theContentResolver
, passing in yourUri
, to get anInputStream
on the content identified by theUri
- Call
reader().readText()
on theInputStream
to get aString
representing the file contents
Combined, that should be something like:
val string = data.data?.let { contentResolver.openInputStream(it).use { it.reader().readText() } }