i create simple application mediaplayer,and i want to get all file .mp3 in device android. below my code :
File home = new File(String.valueOf(Environment.getExternalStorageDirectory()));
if (home.listFiles().length > 0) {
for (File file : home.listFiles()) {
Log.e("test", file.getPath());
if (file.getName().endsWith(".mp3")) {
Log.e("tesnyae", file.getPath());
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
song.put("songPath", file.getPath());
songsList.add(song);
}
}
} else {}
but when i using Environment.getExternalStorageDirectory()
cannot get all .mp3 in device , still available subfolder, if i using specific folder can't get all file,
are there solution to auto get all file .mp3 in android device
You need to recursively loop all the directories to find all the .mp3 files.
You can create a function like this:
public void findAudioInFolder(File folder) {
if (folder.listFiles().length > 0) {
for (File file : folder.listFiles()) {
Log.e("test", file.getPath());
if (file.getName().endsWith(".mp3")) {
Log.e("tesnyae", file.getPath());
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0,(file.getName().length() - 4)));
song.put("songPath", file.getPath());
songsList.add(song);
}
else if (file.isDirectory()) {
findAudioInFolder(file);
}
}
} else {
}
}
And you call it as:
File home = new File(String.valueOf(Environment.getExternalStorageDirectory()));
findAudioInFolder(home);
updated: I realized that there maybe a case that you have a folder named xxx.mp3. So you need to check if the file is a directory first. Modify the code as following:
public void findAudioInFolder(File folder) {
if (folder.listFiles().length > 0) {
for (File file : folder.listFiles()) {
Log.e("test", file.getPath());
if (file.isDirectory()) {
findAudioInFolder(file);
}
else if (file.getName().endsWith(".mp3")) {
Log.e("tesnyae", file.getPath());
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0,(file.getName().length() - 4)));
song.put("songPath", file.getPath());
songsList.add(song);
}
}
} else {
}
}
Hope it will help.