2013-06-20 122 views
1

我試圖製作一個MP3播放器應用程序,當我從手機上運行它時,它只能讀取SD卡上存在的MP3。它不會從卡上存在的子文件夾中讀取任何MP3。我希望它顯示SD卡中的所有MP3(包括子文件夾)。如何訪問SD卡中所有子文件夾中的所有mp3文件?

public class SongsManager { 
// SDCard Path 
final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath()); 
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); 

// Constructor 
public SongsManager(){ 

} 

/** 
* Function to read all mp3 files from sdcard 
* and store the details in ArrayList 
* */ 
public ArrayList<HashMap<String, String>> getPlayList(){ 
    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; 
} 


/** 
* Class to filter files which are having .mp3 extension 
* */ 
class FileExtensionFilter implements FilenameFilter { 
    public boolean accept(File dir, String name) { 
     return (name.endsWith(".mp3") || name.endsWith(".MP3")); 
    } 
} } 
+0

你試過了嗎? – Raghunandan

+0

我試過了這個方法。它仍然不掃描整個SD卡。 – max59

+0

它確實在底部的答案中看到鏈接。它刪除所有.pg文件而不是刪除添加路徑。 – Raghunandan

回答

1
File home = new File(MEDIA_PATH); 

然後

walkdir(home); 

WalkDir方法

public void walkdir(File dir) { 
String Pattern = ".mp3"; 
File listFile[] = dir.listFiles(); 
if (listFile != null) { 
for (int i = 0; i < listFile.length; i++) { 
if (listFile[i].isDirectory()) { 
walkdir(listFile[i]); 
} else { 
if (listFile[i].getName().endsWith(Pattern)){ 
    //Do what ever u want 
    // add the path to hash map  
} 
} 
} 
} 
} 

即使更好地利用增強的for循環通過作爲黑帶建議@

Delete only .jpg files from folder in android

代替刪除將路徑添加到hahsmap中

相關問題