4

I want to write a class which gets all the MP3 files from the whole SD card. But actually it only gets the audio files laying directly on the SD card. So it doesn’t search trough sub folders. I'd like to use Mediastore, but I don’t get it to an arraylist.

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;

import de.me.musicplayer.SongsManager.FileExtensionFilter;

import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;




public class SongsManager {

final String MEDIA_PATH = new String("/sdcard/");
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"));
    }
}
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vinzzenzz
  • 174
  • 2
  • 4
  • 16

4 Answers4

14
final String MEDIA_PATH = Environment.getExternalStorageDirectory()
        .getPath() + "/";
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private String mp3Pattern = ".mp3";

// Constructor
public SongsManager() {

}

/**
 * Function to read all mp3 files and store the details in
 * ArrayList
 * */
public ArrayList<HashMap<String, String>> getPlayList() {
    System.out.println(MEDIA_PATH);
    if (MEDIA_PATH != null) {
        File home = new File(MEDIA_PATH);
        File[] listFiles = home.listFiles();
        if (listFiles != null && listFiles.length > 0) {
            for (File file : listFiles) {
                System.out.println(file.getAbsolutePath());
                if (file.isDirectory()) {
                    scanDirectory(file);
                } else {
                    addSongToList(file);
                }
            }
        }
    }
    // return songs list array
    return songsList;
}

private void scanDirectory(File directory) {
    if (directory != null) {
        File[] listFiles = directory.listFiles();
        if (listFiles != null && listFiles.length > 0) {
            for (File file : listFiles) {
                if (file.isDirectory()) {
                    scanDirectory(file);
                } else {
                    addSongToList(file);
                }

            }
        }
    }
}

private void addSongToList(File song) {
    if (song.getName().endsWith(mp3Pattern)) {
        HashMap<String, String> songMap = new HashMap<String, String>();
        songMap.put("songTitle",
                song.getName().substring(0, (song.getName().length() - 4)));
        songMap.put("songPath", song.getPath());

        // Adding each song to SongList
        songsList.add(songMap);
    }
}
Basbous
  • 3,927
  • 4
  • 34
  • 62
7

You can also fetch using the ContentResolver class.

I have done like this and it's working fine.

    public void getSongListFromStorage() {

        // Retrieve song information
        ContentResolver musicResolver = getContentResolver();
        Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

        if (musicCursor != null && musicCursor.moveToFirst()) {

            // Get columns
            int titleColumn = musicCursor.getColumnIndex
                        (android.provider.MediaStore.Audio.Media.TITLE);
            int idColumn = musicCursor.getColumnIndex
                        (android.provider.MediaStore.Audio.Media._ID);
            int artistColumn = musicCursor.getColumnIndex
                        (android.provider.MediaStore.Audio.Media.ARTIST);

        // Add songs to the list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            songList.add(new Song(thisId, thisTitle, thisArtist));
        } while (musicCursor.moveToNext());

    }

}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vivek Pratap Singh
  • 1,564
  • 16
  • 26
2

This code will give you an arrayList of hash maps whose content is the song title as well as the song's absolute path.

public ArrayList<HashMap<String, String>> getAudioList() {

    ArrayList<HashMap<String, String>> mSongsList = new ArrayList<HashMap<String, String>>();
    Cursor mCursor = getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Audio.Media.DISPLAY_NAME,
                    MediaStore.Audio.Media.DATA }, null, null, null);

    int count = mCursor.getCount();
    System.out.println("total no of songs are=" + count);
    HashMap<String, String> songMap;
    while (mCursor.moveToNext()) {
        songMap = new HashMap<String, String>();
        songMap.put("songTitle",mCursor.getString(mCursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)));
        songMap.put("songPath", mCursor.getString(mCursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
        mSongsList.add(songMap);
    }
    mCursor.close();
    return mSongsList;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0
private void getallaudio()
    {
        String[] STAR = { "*" };
        controller.audioWrapper.clear();
        Cursor audioCursor = ((Activity) cntx).managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, STAR, null, null, null);
        if (audioCursor != null) 
        {
            if (audioCursor.moveToFirst()) 
            {
                do 
                {
                    String path = audioCursor.getString(audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                    audioWrapper.add(new MediaWrapper(new File(path).getName(), path, "Audio",false));
//                    Log.i("Audio Path",path);
                }while (audioCursor.moveToNext());

            }
//            audioCursor.close();
        }
    }
Bhanu Sharma
  • 5,135
  • 2
  • 24
  • 49
  • An explanation would be in order. Did you copy it from somewhere? E.g., what is the idea/gist? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/19680727/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Dec 29 '22 at 21:29