Mount list with files in different folders on android

1

Can anyone give me an idea of how to assemble a list, such as items that are within separate grazing? Example:

folder1: files1 and files2 folder2: files3 and files4

the list would look like: files1 files2 files3 files4

The list I have is as follows:

    File home = new File(MEDIA_PATH);
    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<String, String> song = new HashMap<String, String>();

            song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());

            // Adding each song to SongList
            songsList.add(song);
        }
    }
    // return songs list array
    return songsList;
}

    
asked by anonymous 07.10.2014 / 18:29

1 answer

1

As you are filtering by extension you lose the directories in the listing. For this, I recommend listing everything and using a Filter instance to manually "filter" the files you want, thus maintaining the directories during the iteration.

With this adaptation the code is:

public List<Map<String, String>> listarArquivos(File diretorio) {

    FileExtensionFilter filter = new FileExtensionFilter();
    File[] arquivos = diretorio.listFiles();
    List<Map<String, String>> songsList = new ArrayList<Map<String, String>>();

    if (arquivos.length > 0) {
        for (File file : arquivos) {

            // Se o arquivo que esta iterando for um diretorio
            // É preciso chamar recursivamente essa função para
            // continuar recuperando os arquivos
            if(file.isDirectory()) {
                songsList.addAll(listarArquivos(file));
            } else if(filter.accept(file)) {
                HashMap<String, String> song = new HashMap<String, String>();

                song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
                song.put("songPath", file.getPath());

                // Adding each song to SongList
                songsList.add(song);
            }
        }
    }

    // return songs list array
    return songsList;
}

To call:

List<Map<String, String>> arquivos = listarArquivos(new File(MEDIA_PATH));

The call to accept method will vary depending on which interface the Filter is using:

  • If it is a FileFilter , just use filter.accept(file) ;
  • If it is a FilenameFilter just use filter.accept(diretorio, file)) .
  • An off-topic recommendation: Create a POJO to store the data of songTitle and songPath . Using HashMap to store two attributes is much more costly than creating an object with two attributes.

        
    08.10.2014 / 02:29