android scanning all .mp3 files in SD Card

前端 未结 5 764

I\'m trying to scan all .mp3 files in my SD card and save its name. here is a fragment of code which is responsible for that. 1.What i\'m doing wrong? 1. Which is correct

5条回答
  •  执笔经年
    2021-01-16 03:16

    try this code snippet

    final String MEDIA_PATH = Environment.getExternalStorageDirectory()
            .getPath() + "/";
    private ArrayList> songsList = new ArrayList>();
    private String mp3Pattern = ".mp3";
    
    // Constructor
    public SongsManager() {
    
    }
    
    /**
     * Function to read all mp3 files and store the details in
     * ArrayList
     * */
    public ArrayList> getPlayList() {
        System.out.println(MEDIA_PATH);
        if (MEDIA_PATH != null) {
            File home = new File(MEDIA_PATH);
            File[] listFiles = home.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    System.out.println(file.getAbsolutePath());
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }
                }
            }
        }
        // return songs list array
        return songsList;
    }
    
    private void scanDirectory(File directory) {
        if (directory != null) {
            File[] listFiles = directory.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }
    
                }
            }
        }
    }
    
    private void addSongToList(File song) {
        if (song.getName().endsWith(mp3Pattern)) {
            HashMap songMap = new HashMap();
            songMap.put("songTitle",
                    song.getName().substring(0, (song.getName().length() - 4)));
            songMap.put("songPath", song.getPath());
    
            // Adding each song to SongList
            songsList.add(songMap);
        }
    }
    

提交回复
热议问题