Mansour Fahad Mansour Fahad - 1 year ago 78
Android Question

How to look up for all files in an android device and put them in a list?

I looking for help to list all files in android external storage device. I want to look up in all the folders including the subfolders for the main folder. Is there any way to this?

I have worked on a basic one but still haven't get the desired result. It doesn't work.
Here is my code:

File[] files_array;
files_array = new File(Environment.getExternalStorageDirectory().getAbsolutePath()).listFiles();

Please help. Thank you.


This method returns 0 size. I don’t know what is the matter. This is my activity:

public class Main extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
List<File> files = getListFiles(Environment.getExternalStorageDirectory());
setListAdapter(new ArrayAdapter<File>(Main.this, android.R.layout.simple_list_item_1, files));
Toast.makeText(this, "" + files.size(), Toast.LENGTH_LONG).show();

private List<File> getListFiles(File parentDir) {
// On first call, parentDir is your sdcard root path
ArrayList<File> inFiles = new ArrayList<File>(); // initialize an array list to store file names
File[] files = parentDir.listFiles(); // list all files in this directory
for (File file : files) {
if (file.isDirectory()) { // if the file is a directory
inFiles.addAll(getListFiles(file)); // **CALL THIS RECURSIVELY TO GET ALL LOWER LEVEL FILES**

return inFiles;

Answer Source

I have found a solution somewhere on the web and I asked my self why not share it.

        public void walkdir(File dir) {

        File[] listFile;
        listFile = dir.listFiles();

        if (listFile != null) {
            for (int i = 0; i < listFile.length; i++) {
                if (listFile[i].isDirectory()) {
                } else {
                  if (listFile[i].getName().toLowerCase().endsWith(".pdf")){

All what you need actually is calling the method above with the parent dir that you want to start with. I recommend to put Environment.getExternalStorageDirectory() in the parent directory so it will not change with different devices.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download