0

I am building music player app for that I gathering data from SDcard which downloaded from the server and save files name into ArrayList

private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

Now the problem is I want to play mp3 file according to the user click on recycler item so for that, I want index number for the particular name.

How can I get an index for passing name of the mp3 file??

/**
     * 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());

                Log.d(TAG, "getPlayList() called title = "+file.getName().substring(0, (file.getName().length() - 4))+"  Path = "+file.getPath());
                // Adding each song to SongList
                songsList.add(song);
            }
        }
        // return songs list array
        return songsList;
    }
2
  • 3
    I advise you to make a Song class instead of storing properties in a HashMap Commented May 4, 2017 at 9:22
  • yes, POJO would be a good option but I already implemented HashMap so now it will take a time to implement and changes in all classes. Commented May 4, 2017 at 9:28

1 Answer 1

2

With your construction, you could loop over the list to find the map you need

int indexForSongName(String songName) {
    ArrayList<HashMap<String, String>> playlist = getPlayList();

    for (int i = 0; i < playlist.size(); i++) {
        HashMap<String, String> map = playlist.get(i);
        if (map.containsValue(songName)) { // Or map.getOrDefault("songTitle", "").equals(songName);
            return i;
        }
    }

    return -1; // Not found.
}

That said, I advise you to make a Song class instead of storing properties in a HashMap. It is good practice and it would make tasks such as these easier.

Sign up to request clarification or add additional context in comments.

2 Comments

i will try your answer and let you know
Thank you, genius its work like charm and I will remember your advice in future

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.