Unable to read files from an external file location in Android's external storage

Viewed 82

I am trying to access files stored in my phone's external location and read them. Here's my code snippet:


    logsDir = File(dir, "TestFiles")
    val logFiles = logsDir.listFiles() 
    Timber.i("logsDir = $logsDir") 
    Timber.i("isDirectory = ${logsDir.isDirectory}") 
    Timber.i("exists = ${logsDir.exists()}") 
    Timber.i("size ${logsDir.listFiles().size}") 
    logFiles?.forEach {
        Timber.i("${it.name}") 
    }

Here's the output:

logsDir = /storage/emulated/0/TestFiles
isDirectory = true
exists = true
size = 0

For some reason, it can't find any files in that directory when I can see those files through the file directory structure. These are .json and .txt files that I added into this directory. I have all the correct READ and WRITE permissions added to the manifest. But I have no idea why it can't see any files within the directory.

I saw a related post and tried the solutions given there but none worked. File exists and IS directory, but listFiles() returns null

Please help!

1 Answers

Add the following Application tag in the Android Manifest file:

<application
        ....
        android:requestLegacyExternalStorage="true">
Related