0

How to get real file path from URI while using storage access framework in android Q and android R. My code to pick pdf file using system file picker i.e.

 Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                    type = "application/pdf"
                    addCategory(Intent.CATEGORY_OPENABLE)
                    flags = flags or Intent.FLAG_GRANT_READ_URI_PERMISSION
                    startActivityForResult(intent, OPEN_PDF_REQUEST)
                }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == OPEN_PDF_REQUEST && resultCode == RESULT_OK) {
            data?.data?.also { documentUri ->

                //Permission needed if you want to retain access even after reboot
                contentResolver.takePersistableUriPermission(
                    documentUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION
                )

                val documentFile = DocumentFile.fromSingleUri(this, documentUri)

                val fileUri = documentFile?.uri
                Log.d("TAG", "path = ${fileUri?.path}")

            }
        }
    }

Logcat OUTPUT

URI= content://com.android.providers.media.documents/document/document%3A266

I am unable to get real file path from this URI in order to open the file within PdfViewer and also unable to open this URI in PDFViewer.

Now, how to get real file path from this URI or any alternative solution in order to achieve this goal (i.e. open pdf file in pdf viewer) in android Q and above.

Any help will be appreciated :)

  • There is nothing named PdfViewer or PDFViewer in the Android SDK. If you are using a PDF viewer from a library, provide us a link to the library, and perhaps we can make some suggestions. – CommonsWare Apr 23 '21 at 16:31
  • I am using a library to view pdf files, here its link https://github.com/barteksc/AndroidPdfViewer – Arsalan Khan Apr 23 '21 at 16:57
  • Not necessary to view pdf files, it could be any file like to view MHT format file in webview etc. Need how to get real file path from URI or in android Q and above how to pick file from device storage and view it – Arsalan Khan Apr 23 '21 at 16:59
  • "I am using a library to view pdf files" -- [the documentation](https://github.com/barteksc/AndroidPdfViewer#load-a-pdf-file) shows a `fromUri()` method. "Need how to get real file path from URI" -- there is no "real file path". There is no requirement for the `Uri` to represent a file, let alone one that your app can access. This is not significantly different than an `https` URL, such as the one for this Web page. – CommonsWare Apr 23 '21 at 17:08

0 Answers0