List All Mp3 files in android

前端 未结 4 912
日久生厌
日久生厌 2021-02-03 16:28

I am developing music player in android but stuck in reading MP3 files. here is my code to read all mp3 files. but its not returing any files from device(although there are some

4条回答
  •  悲&欢浪女
    2021-02-03 17:06

    here I've modified your getPlayList() method. look into it.

    ArrayList> getPlayList(String rootPath) {
                ArrayList> fileList = new ArrayList<>();
    
    
                try {
                    File rootFolder = new File(rootPath);
                    File[] files = rootFolder.listFiles(); //here you will get NPE if directory doesn't contains  any file,handle it like this.
                    for (File file : files) {
                        if (file.isDirectory()) {
                            if (getPlayList(file.getAbsolutePath()) != null) {
                                fileList.addAll(getPlayList(file.getAbsolutePath()));
                            } else {
                                break;
                            }
                        } else if (file.getName().endsWith(".mp3")) {
                            HashMap song = new HashMap<>();
                            song.put("file_path", file.getAbsolutePath());
                            song.put("file_name", file.getName());
                            fileList.add(song);
                        }
                    }
                    return fileList;
                } catch (Exception e) {
                    return null;
                }
            }
    

    you can get the song name and song path like this:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    ArrayList> songList=getPlayList("/storage/sdcard1/");
            if(songList!=null){
            for(int i=0;i
    
    
    

    Hope this will help you.

提交回复
热议问题