0

I want to get content (images & videos) of user selected folder. Code to select the folder is:

val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                    or Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
                    or Intent.FLAG_GRANT_READ_URI_PERMISSION
                    or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
        )
startActivityForResult(intent, 1088)

And onActivityResult, I am persisting the permission(even I tested without restarting the device but it is not working):

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode == Activity.RESULT_OK) {
           if (requestCode == 1088) {
               val selectedDirUri = data!!.data

                grantUriPermission(packageName, selectedDirUri, (Intent.FLAG_GRANT_READ_URI_PERMISSION
                        or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION))

                val takeFlags = (data.flags
                        and (Intent.FLAG_GRANT_READ_URI_PERMISSION
                        or Intent.FLAG_GRANT_WRITE_URI_PERMISSION))
                contentResolver.takePersistableUriPermission(selectedDirUri!!, takeFlags)
             }
        }
   }

And I am traversing through all files using:

val rootUri: Uri = Uri.parse(selectedDir)

            val contentResolver: ContentResolver = context.contentResolver
            var childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, DocumentsContract.getTreeDocumentId(rootUri))

            val dirNodes: MutableList<Uri> = LinkedList()
            dirNodes.add(childrenUri)

            while (!dirNodes.isEmpty()) {
                childrenUri = dirNodes.removeAt(0) // get the item from top
                
                val c = contentResolver.query(childrenUri,
                    arrayOf(
                        DocumentsContract.Document.COLUMN_DOCUMENT_ID,
                        DocumentsContract.Document.COLUMN_DISPLAY_NAME,
                        DocumentsContract.Document.COLUMN_MIME_TYPE,
                        DocumentsContract.Document.COLUMN_LAST_MODIFIED),
                    null, null, null)
                try {
                    while (c!!.moveToNext()) {
                        val docId = c.getString(0)
                        val fileName = c.getString(1)
                        val mimeType = c.getString(2)
                        val lastModified = c.getLong(3)
                        
                        if (isDirectory(mimeType)) {
                            

                            val newNode = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, docId)
                            dirNodes.add(newNode)
                        } else {
                            

                            val newNode = DocumentsContract.buildDocumentUriUsingTree(rootUri, docId)
                            Logger.log("TAG", "========1 Images: $newNode")
                            
                            val ***sourceFileUri*** = newNode.toString()
                        }
                    }
                } finally {
                    closeQuietly(c)
                }
            }

Then I display images and videos using Glide, it is not displaying. Even if I try to copy the image using below code:

val inputStream: InputStream? = context.contentResolver.openInputStream(***sourceFileUri***)

I am getting below error, the above line gives an error:

java.lang.SecurityException: com.android.externalstorage has no access to content://media/external _primary/file/1000008384 at android.os.Parcel.createException or Null(Parcel.java:2438) at 08 android.os.Parcel.createException(P arcel.java:2422) at android.os.Parcel.readException(Par cel.java:2405) at android.database.DatabaseUtils.rea dExceptionFromParcel(DatabaseUtil s.java:190) at android.database.DatabaseUtils.rea dException WithFileNotFoundExcepti on From Parcel(DatabaseUtils.java:15 3)

This is happening in Vivo, Oppo and specially in new Samsung phones only which has android OS 11 and 12. I am really frustrated, I tried all possible solution but not able to find any solution till now.

Any solution or advice would be really helpful and appreciated, please please help me.

Smeet
  • 4,036
  • 1
  • 36
  • 47
  • Please remove all flags from OPEN_DOCUMENT_TREE intent. They do nothing. – blackapps Nov 09 '22 at 07:09
  • Please remove the call to grantUriPermission() as it does nothing. – blackapps Nov 09 '22 at 07:10
  • You did not show how you obtained the `sourceFileUri`s. – blackapps Nov 09 '22 at 07:13
  • @blackapps I added that line in my question. And regarding flags and grantUriPermission(), if I remove, will it work or it is just not necessary as you mentioned that is does nothing? Please check updated question. – Smeet Nov 09 '22 at 07:57
  • A childuri is no sourceFileUri. So we know nothing more yet. And you are not showing how you use Glide. – blackapps Nov 09 '22 at 08:10
  • Further it is still unclear which statement gives the error. – blackapps Nov 09 '22 at 08:12
  • @blackapps I added more lines of code to show how I am getting sourceFileUri. Forget about glide but when I read the file using above line val inputStream: InputStream? = context.contentResolver.openInputStream(***sourceFileUri***) I am getting error. Hope you clear now and it is not more understandable. – Smeet Nov 09 '22 at 08:29
  • Ok. Please tell the value of selectedDir.toString() and of selectedFileUri.toString(). – blackapps Nov 09 '22 at 08:34
  • `context.contentResolver.openInputStream(***sourceFileUri***)` But sourceFileUri was a string. Not an uri. It should have been context.contentResolver.openInputStream(newNode). How could it even compile? – blackapps Nov 09 '22 at 08:37
  • Please ignore spaces from above uri path, it is: content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia/document/primary%3AAndroid%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia%2F.Statuses%2Fc7a8aa99d18c4906815845ae1cb9c8c1.mp4 – Smeet Nov 09 '22 at 09:39
  • I had rather seen you posted those uri strings in your post. Anyhow I have no idea where this content://media/external _primary/file/1000008384 comes from. It looks as if you did not post all relevant code. – blackapps Nov 09 '22 at 10:44
  • The url string for the selected dir is strange as it contains twice primary. Never seen such. – blackapps Nov 09 '22 at 10:52
  • content://media/external _primary/file/1000008384 is shown in log cat error message only. But I am also not sure why it is throwing exception like this but I assume it gives error msg of related root directory path ? Really sorry for selected dir, it is: content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia – Smeet Nov 09 '22 at 11:24
  • Rather than manually using `DocumentsContract`, consider using `DocumentFile`. However, overall, I would not expect you to be able to access content in the app-specific external storage of WhatsApp, unless you are a WhatsApp app developer. – CommonsWare Nov 09 '22 at 13:16
  • @CommonsWare I tried using DocumentFile as well like : val documentFile = DocumentFile.fromTreeUri(context, rootUri) and documentFile!!.listFiles() but it gives the same path/URI: content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia/document/primary%3AAndroid%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia%2F.Statuses%2FIMG-20210701-WA0005.jpg This URI I am using to read the file so it will not make any difference. Any other highlights please ? – Smeet Nov 09 '22 at 13:48
  • As I wrote, I would not expect you to be able to access WhatsApp's app-specific content. – CommonsWare Nov 09 '22 at 13:55
  • @CommonsWare I can understand but according to what google advertising in their docs, if you want to access third party app content, you can use SAF API. So I am surprised and wondering is there any issue in my code or some problem in some device's customized OS. – Smeet Nov 09 '22 at 15:14
  • @blackapps Any inputs on this please ? – Smeet Nov 09 '22 at 15:15

0 Answers0