2011-11-18 24 views
0

我想從SD卡中的MP3文件,並把它們放在一個ListView爲什麼這個代碼不工作,將元素添加到歌曲名稱問題添加字符串列表<String>

String[] proj = { MediaStore.Audio.Media._ID, 
        MediaStore.Audio.Media.DATA, 
        MediaStore.Audio.Media.DISPLAY_NAME, 
        MediaStore.Audio.Artists.ARTIST }; 
Cursor tempCursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
           proj, 
           null, 
           null, 
           null); 
tempCursor.moveToFirst(); //reset the cursor 
int col_index=-1; 
int numSongs=tempCursor.getCount(); 
int currentNum=0; 
do{ 
    col_index = tempCursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST); 
    List<String> songname = new ArrayList<String>(); 
    if(tempCursor.moveToNext()){ 
     songname.add(tempCursor.getString(currentNum+1)); 
     ArrayAdapter<String> songss = new ArrayAdapter<String>(this, R.id.songs,songname); 
     setListAdapter(songss); 
    } else{ 
     return; 
    } 
    currentNum++; 
}while (tempCursor.moveToNext()); 
+0

它給出了什麼錯誤。 – Rocker

回答

0

當它弄亂這條線應該是做的外... while()循環

List<String> songname = new ArrayList<String>(); 

的循環迭代,每次SONGNAME將與新的對象存儲定義,你只拿到了最後一個名字。也simillary這段代碼while循環

ArrayAdapter<String> songss = new ArrayAdapter<String>(this, R.id.songs,songname); 
setListAdapter(songss); 

這裏後是完整的代碼

String[] proj = { MediaStore.Audio.Media._ID, 
        MediaStore.Audio.Media.DATA, 
        MediaStore.Audio.Media.DISPLAY_NAME, 
        MediaStore.Audio.Artists.ARTIST }; 
Cursor tempCursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
           proj, 
           null, 
           null, 
           null); 

int col_index=-1; 
int numSongs=tempCursor.getCount(); 
int currentNum=0; 
List<String> songname = new ArrayList<String>(); 
while (tempCursor.moveToNext()) 
    col_index = tempCursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST); 

    songname.add(tempCursor.getString()); // here you need the column index number of song title name only 
} 

ArrayAdapter<String> songss = new ArrayAdapter<String>(this, R.id.songs,songname); 
setListAdapter(songss); 
+0

非常感謝你,我會嘗試。亞勒一直是一個很大的幫助...謝謝 –

0

這段代碼並沒有太大的意義,什麼是你想怎麼辦?

List<String> songNames = new ArrayList<String>(); 
Cursor c = grabCursorWithSongs(); 
try { 
    while (c.moveToNext()) { 
     String songName = c.getString(c.getColumnIndex("song_name")); 
     songNames.add(songName); 
    } 
} finally { 
    c.close(); 
} 
ArrayAdapter<String> adapter = new ArrayAdapter<String>(...); 
setListAdapter(adapter); 
+0

它只是強制關閉當我跑步。 ....我試圖做一個MP3播放器的應用程序,這部分的代碼是假設從SD卡上的歌曲,並將它們添加到列表視圖 –

相關問題