从ArrayList获取索引<hashmap <string,string =“”>&gt;

时间:2017-05-04 09:17:30

标签: android arraylist

我正在构建音乐播放器应用程序,我从SDcard收集数据,从服务器下载并将文件名保存到 ArrayList

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

现在问题是我想根据用户点击回收商项目来播放mp3文件,所以我想要特定名称的索引编号。

如何获取传递mp3文件名的索引

/**
     * 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;
    }

1 个答案:

答案 0 :(得分:2)

根据您的构造,您可以遍历列表以查找所需的地图

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.
}

那就是说,我建议你制作一个Song类,而不是在HashMap中存储属性。这是一种很好的做法,它可以使这些任务变得更容易。