我正在尝试从SD卡中获取mp3文件并将它们放在listview上为什么这段代码无法正常工作时将元素添加到歌曲名称时会搞砸
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 :(得分:0)
这一行应该在do ... 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);
答案 1 :(得分: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);