2017-05-04 144 views
0

我建立的音樂播放器應用程序從SD卡從服務器上下載,我收集數據和保存文件命名爲ArrayList中獲得指數<HashMap的<字符串,字符串>>

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; 
    } 
+3

我建議你做一個'Song'類而不是在HashMap中存儲屬性 –

+0

是的,POJO是一個很好的選擇,但是我已經實現了HashMap,所以現在需要一段時間來實現和更改所有的類。 –

回答

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

不過,我建議你做的,而不是在一個HashMap存儲性能的宋級。這是很好的做法,它會使這些任務更容易。

+0

我會嘗試你的答案,並讓你知道 –

+0

謝謝你,天才它的工作像魅力,我會記住你的建議在未來 –

相關問題