Android File.listFiles() returns only subdirectories

Tags: , ,



I am trying to get all files and subdirectories in directory and show their names. This is the code I use:

File internalStorageDir = new File(Environment.getExternalStorageDirectory().getPath());
File[] files = internalStorageDir.listFiles();
ArrayList<String> fileNames = new ArrayList<>();
for(int i=0; i< files.length; i++){fileNames.add(files[i].getName());}

The specified directory(Environment.getExternalStorageDirectory()) contains files and subdirectories, but listFiles() only returns subdirectories. What’s wrong with this code? Permission to read external storage has already been granted.

Answer

My fault, I missed something. In Android 11, you can only access media files. In my case, the files in external storage were not media files, so they were not displayed. But after changing the target api to 29 (Android 10) everything works fine. Thanks to everyone who tried to help!



Source: stackoverflow