androidkotlinstorage-access-frameworksaf

Unable to find folders in the directory tree in Android (Kotlin)


I'm encountering difficulties in my Android application while attempting to access and process folders within a directory tree. The provided code snippet aims to traverse a directory tree and identify folders for further processing. However, despite the presence of folders in the specified directory, the code doesn't seem to recognize or retrieve these folders using listFiles(). This behavior persists despite correct directory URIs being passed.

private fun processDirectoryPath(directoryUri: Uri) {
    val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(
        directoryUri,
        DocumentsContract.getTreeDocumentId(directoryUri)
    )
    Log.d("Folder Manager", "DEBUG?$directoryUri")
    val docTree = DocumentFile.fromTreeUri(this, childrenUri)
    val images = ArrayList<Pair<String, Bitmap>>()
    var errorFound = false
    if (docTree!!.listFiles().isNotEmpty()) {
        for (doc in docTree.listFiles()) {
            if (doc.isDirectory && !errorFound) {

                // ...
            }
        }
    }

    // ...
}

I've implemented the code to traverse the directory tree using DocumentsContract.buildChildDocumentsUriUsingTree and DocumentFile.fromTreeUri. I expected the listFiles() method to return the list of folders within the specified directory tree. However, it appears that the listFiles() call doesn't recognize the folders, resulting in an empty list or no traversal into the directories.


Solution

  • Considering the document tree created by my app from another function, I attempted using File.listFiles() as an alternative to address the issue.

        private fun processDirectoryPath(directoryPath: String) {
        val files = File(directoryPath).listFiles()
        val images = ArrayList<Pair<String, Bitmap>>()
        var errorFound = false
    
        if (files != null) {
            for (file in files) {
                if (file.isDirectory) {
                    // ....
                }
            }
        }
    }