Scooped storage API not returning proper File count from SD card folder and Private files folder on Android 11

94 views Asked by At

I have an Android 11 device. Which has SD Card. Given app has ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION. The app creates the folder on the SD card with NJFiles programmatically.

Then the App adds 4000 dummy files to

NJFiles and App private folder

enter image description here

/Android/data/com.nj.scopedstorage/files

enter image description here

Code that add 4k file is as below

private fun addFiles() {
    Thread {
        runOnUiThread {
            findViewById<MaterialButton>(R.id.addFilesToFolder).text =
                "File Creation InProgress"
        }
        //get folder name
        val privateFileFolder = getSdCardPath(this)
        val sdCardRoot =
            privateFileFolder?.removeSuffix(privateDataFilesFolder)

        for (i in 0 until 4000) {
            val filePrivate = File("${privateFileFolder}/file${i}.txt")
            val fileSdCard = File("${sdCardRoot}/$sdCardNjFolder/file${i}.txt")
            filePrivate.createNewFile()
            fileSdCard.createNewFile()
        }

        runOnUiThread {
            findViewById<MaterialButton>(R.id.addFilesToFolder).text =
                "Add Dummy Files in Folders"
        }
    }.start()
}

Whenever I try to list the files in both folders I am getting 0 as files.

I used the below code to get the files from the folder.

private fun getFilesFromFolder(
    context: Context,
    fileNames: HashSet<String>,
    privateFolder: Boolean
): HashSet<String>? {
    try {
        val projection = arrayOf(MediaStore.Files.FileColumns.DISPLAY_NAME)
        val selection = MediaStore.MediaColumns.DATA + " LIKE ? "
        val selectionArgs: Array<String> = if (privateFolder) {
            arrayOf(privateDataFilesFolder)
        } else {
            arrayOf(sdCardNjFolder)
        }
        val cursor = context.contentResolver.query(
            MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL),
            projection,
            selection,
            selectionArgs,
            null
        )
        if (cursor != null) {
            while (cursor.moveToNext()) {
                fileNames.add(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME)))
            }
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
    return fileNames
}

Whenever I tries to list the files in both folders I am getting 0 as files, expected it 4K files count.

1

There are 1 answers

1
blackapps On

The MediaStore will never index files in private .../Android/data/<package> folders.

For the NJFiles folder you should first let the MediaStore index/scan those files.

Or reboot your device.

Better do the listings with File.listFiles().