Question

How to fetch only folders name from SD card into a ListView?

In one of my Church Application, I am allowing user to create an event (example: Phase-I Church - Evening Prayer_Part1), and then creating a folder with same name into

SD Card/Church Application/EventNameFolders

So now my target is to show all folders name from Church Application into ListView.

Was it helpful?

Solution

private ListView lv = (ListView) findViewById(R.id.your_list_view_id);

List<String> your_array_list = new ArrayList<String>();
String path = Environment.getExternalStorageDirectory().toString()+"/Church Application/";

File f = new File(path);
File[] files = f.listFiles();
for (File inFile : files) {
    if (inFile.isDirectory()) {
        // in here, you can add directory names into an ArrayList and populate your ListView.
        your_array_list.add(inFile.getName());
    }
}

 ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                 this, 
                 android.R.layout.simple_list_item_1,
                 your_array_list );

         lv.setAdapter(arrayAdapter);

Delete empty folders

String path = Environment.getExternalStorageDirectory().toString()+"/Church Application/";

File f = new File(path);
File[] files = f.listFiles();
for (File inFile : files) {
    if (inFile.isDirectory()) {
        // If this folder is empty, delete it.
        if (inFile.listFiles().length == 0) {
            inFile.delete();
        }
    }
}

Delete empty folders and Display only folders which are not empty

private ListView lv = (ListView) findViewById(R.id.your_list_view_id);

List<String> your_array_list = new ArrayList<String>();
String path = Environment.getExternalStorageDirectory().toString()+"/Church Application/";

File f = new File(path);
File[] files = f.listFiles();
for (File inFile : files) {
    if (inFile.isDirectory()) {
        // If this folder is empty, delete it.
        if (inFile.listFiles().length == 0) {
            inFile.delete();
         // If not, add to ArrayList 
        } else if (inFile.listFiles().length >= 1) {
            your_array_list.add(inFile.getName());
        } 
    }
}

 ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                 this, 
                 android.R.layout.simple_list_item_1,
                 your_array_list );

         lv.setAdapter(arrayAdapter);

OTHER TIPS

File[] file = Environment.getExternalStorageDirectory().listFiles();  


        for (File f : file)
        {
            if (f.isDirectory()) { 
                 file[] innerFiles = f.listFiles();

                 for(int i=0; i< innerFiles.length;i++){
                   Log.i("Name", innerFiles[i].getPath() + "");
                 }
        }

            if (f.isFile()) {your code}
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top