I am trying to get the uri for the pdf document stored in documents folder on actual android device.
Actual doc path on device is
/storage/emulated/0/Documents/testme.pdf
to get the uri for this file this is the code I have tried
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && requestCode == FILE_BROWSER_REQUEST_CODE) {
val uri: Uri? = data!!.getData() // - content://com.android.providers.media.documents/document/document:30082
val fileTest = File(uri!!.path) // /document/document:30082
if(fileTest.exists() && fileTest.canRead()) { // both are FALSE
Toast.makeText(context, "fileTest exists", Toast.LENGTH_LONG).show()
}
}
}
getting the file from uri definitely is not the right way I am doing
how can I get the right uri please
your help is much appreciated
Thanks R
CodePudding user response:
You cannot get a File from an Uri. An Uri can only be used by a DocumentFile.
The Uri you need is stored in your "uri" variable.
I recommend reading something about DocumentFiles here https://developer.android.com/reference/androidx/documentfile/provider/DocumentFile
CodePudding user response:
You can use Scoped Storage API to get the document.
Just use the system file picker to get the URI.
- Create a Contract class
class FilePickerContract : ActivityResultContract<Unit, List<Uri>>() {
override fun createIntent(context: Context, input: Unit?): Intent =
Intent(Intent.ACTION_GET_CONTENT).setType("*/*").putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
override fun parseResult(resultCode: Int, intent: Intent?): List<Uri> = if (resultCode != Activity.RESULT_OK || intent == null) {
emptyList()
} else {
val uris = mutableListOf<Uri>()
intent.data
?.let {
uris.add(it)
}
?: intent.clipData?.let { clipData ->
for (i in 0 until clipData.itemCount) {
uris.add(clipData.getItemAt(i).uri)
}
}
uris
}
}
- Create an instance of the Contract
private val filePickerResultContract = registerForActivityResult(FilePickerContract()) { uris: List<Uri> ->
if (uris.isNotEmpty()) {
// do something with uris...
} else {
// no uris
}
}
- Launch the contract
filePickerResultContract.launch(Unit)
You can read more about Android SAF here

