I am developing an app in which I am generating the list of all mp3 files and adding it in a custom list. I have a program for this but the problem is that it doesn't return the files inside the subfolder.
Can anyone advise me or give a link or something so that I can do it iteratively? I want to do it iteratively because if I don't do so, I will have to pass a lot of information between methods and it will become really confusing. I tried doing that and ended up totally confused.
Here is the code:
public class FragmentSongs extends Fragment {
private static final String Sd_Path=new String("/sdcard/");
private MediaPlayer mp =new MediaPlayer();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
ListView SngList = (ListView) view.findViewById(R.id.SongList);
ArrayList<SongDetails> Songinfo;
// AdapterView.AdapterContextMenuInfo info;
Songinfo = new ArrayList<SongDetails>();
File f=new File("/sdcard/");
File[] files = f.listFiles(new Mp3Filter());
if( files.length>0)
{
for(int i=0; i<files.length; i++)
{SongDetails detail=new SongDetails();
detail.setIcon(R.drawable.ic_launcher);
detail.setSong(files[i].getName());
detail.setArtist(files[i].getName());
detail.setAlbum(files[i].getName());
Songinfo.add(detail);
} SngList.setAdapter(new CustomAdapter(Songinfo ));
}
else if (files.length == 0)
return null;
return view;
} }
class Mp3Filter implements FilenameFilter{
public boolean accept(File dir,String name)
{
return (name.endsWith(".mp3"))|| (name.endsWith(".Mp3")) ||(name.endsWith(".MP3"));//searching for the files
}
}
Add a separate method to your activity that does the following:
private ArrayList<SongDetails> getSongsFromDirectory(File f){
ArrayList<SongDetails> songs = new ArrayList<SongDetails>();
if (!f.exists() || !f.isDirectory()) return songs;
File[] files = f.listFiles(new Mp3Filter());
for (File file : files){
if (file.isDirectory()){
songs.addAll(getSongsFromDirectory(file));
}
else{
SongDetails detail=new SongDetails();
detail.setIcon(R.drawable.ic_launcher);
String fileName = file.getName();
detail.setSong(fileName);
detail.setArtist(fileName);
detail.setAlbum(fileName);
songs.add(detail);
}
}
return songs;
}
Also change your filter to a FileFilter and also return folders
class Mp3Filter implements FileFilter{
public boolean accept(File file){
return (file.isDirectory() || file.getName().toUpperCase().endsWith(".MP3"))
}
}
Finally, change your code in onCreateView to this:
View view = inflater.inflate(R.layout.fragment_a, container, false);
ListView SngList = (ListView) view.findViewById(R.id.SongList);
File f=new File("/sdcard/");
ArrayList<SongDetails> Songinfo = getSongsFromDirectory(f);
if (songinfo.size()>0){
SngList.setAdapter(new CustomAdapter(Songinfo));
return view;
}
else return null;
Please note that I did not test this code, but it should at least give you an idea of how to accomplish it.