Android Studio music player cant read from sdcard, only internal memory

与世无争的帅哥 提交于 2019-12-03 20:08:28

Use this method to get the list of filePath from your device

 ArrayList<String> findSongs(String rootPath) {
    ArrayList<String> 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 (findSongs(file.getAbsolutePath()) != null) {
                    fileList.addAll(findSongs(file.getAbsolutePath()));
                } else {
                    break;
                }
         } else if (file.getName().endsWith(".mp3")) {
             fileList.add(file.getAbsolutePath());
         }
    }
    return fileList;
    }catch(Exception e){
       return null;
    }
}

but you need to get files from sdCard, for that pass "/storage/sdcard1/" as the parameter for findSongs(String path) method like this:

onCreate(Bundle svaeInstance){
 ........
 ........
  if(findSongs("/storage/sdcard1/")!=null){
    ArrayList<String> listOfFilePath=findSongs("/storage/sdcard1/"); // here you will get all the files path which contains .mp3 at the end.
 //do the remaining stuff
  }else { Toast.makeText(this, "sdCard not available", Toast.LENGTH_SHORT).show();
  }
 ......
}

Note: use "/storage/sdcard1/" for reading files from sdCard and use Environment.getExternalStorageDirectory().getAbsolutePath() for reading files from phone memory.

Hope this will help you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!