我试图列出我的SD卡中可用的所有歌曲专辑。我做得很成功,但我遇到了一个小问题。例如,如果我是一张专辑" ABC",其中包含10位艺术家。然后,当我查询专辑时,它会显示专辑" ABC" 10次基于艺术家。专辑" ABC"将显示10次,每张专辑" ABC"将包含特定艺术家的歌曲。
显示如下,
ABC\artistA
ABC\artistB
........等等
我想要的是它应该显示专辑" ABC"有一次当我打开它时,那张专辑中的所有歌曲都应该在那里。
代码:
final Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
final String _id = MediaStore.Audio.Albums._ID;
final String album_name = MediaStore.Audio.Albums.ALBUM;
final String totSongs = MediaStore.Audio.Albums.NUMBER_OF_SONGS;
final String artist_Name = MediaStore.Audio.Albums.ARTIST;
final String[] columns = { _id, album_name, totSongs,artist_Name };
Cursor cursor = getActivity().getContentResolver().query(uri, columns, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
id = cursor.getLong(cursor.getColumnIndex(_id));
String name = cursor.getString(cursor.getColumnIndex(album_name));
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
albumArtUri = ContentUris.withAppendedId(sArtworkUri, id).toString();
totalSongs = cursor.getString(cursor.getColumnIndex(totSongs));
ArtistName = cursor.getString(cursor.getColumnIndex(artist_Name));
AlbumsModel s = new AlbumsModel(id, name, albumArtUri,totalSongs,ArtistName);
AlbumsList.add(s);
} while (cursor.moveToNext());
}
cursor.close();
答案 0 :(得分:0)
您可以使用List
:
Map
HashMap<String, AlbumModel> albums = new HashMap();
Cursor cursor = getActivity().getContentResolver().query(uri, columns, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
id = cursor.getLong(cursor.getColumnIndex(_id));
String name = cursor.getString(cursor.getColumnIndex(album_name));
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
albumArtUri = ContentUris.withAppendedId(sArtworkUri, id).toString();
totalSongs = cursor.getString(cursor.getColumnIndex(totSongs));
ArtistName = cursor.getString(cursor.getColumnIndex(artist_Name));
AlbumsModel album = albums.get(id);
if(album == null){
album = new AlbumsModel(id, name, albumArtUri,totalSongs,ArtistName);
albums.put(id, album);
continue;
}
//update album music count
album.setTotalMusic(album.getTotalMusic() + totSongs);
albums.put(id, album);
} while (cursor.moveToNext());
}
cursor.close();
答案 1 :(得分:0)
这就是你可以显示Album / Artist与Album只出现一次的方式(假设光标按专辑排序): -
String previous_album = "";
for (AlbumsModel am: AlbumsList) {
if(am.getAlbumName().equals(previous_album)) {
Log.d("ALBUMINFO","\t\t" + am.getArtistName());
} else {
Log.d("ALBUMINFO",am.getAlbumName() + "\t" + am.getArtistName());
}
previous_album = am.getAlbumName();
}
这将遵循您的代码并将输出写入日志(显然您可以根据需要进行定制),例如: -
01-24 20:54:21.705 2125-2125/albums.so.so48422731albums D/ALBUMINFO: ABC ArtistA
01-24 20:54:21.705 2125-2125/albums.so.so48422731albums D/ALBUMINFO: ArtistB
01-24 20:54:21.705 2125-2125/albums.so.so48422731albums D/ALBUMINFO: ArtistC