Search code examples
javaandroidandroid-contentresolvermediastore

Android ContentResolver doesn't load the Song-Titles


My App should load the Media-Tags from the Songs, stored on the Device's storage, but the displayed Names are the File-Names and not the Title-Tags!

My Code:

List<Song> SongList = new ArrayList<>();

ContentResolver musicResolver = mContext.getContentResolver();

Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

Cursor cSong = musicResolver.query(musicUri, null, null, null, null);

int iIDCol = cSong.getColumnIndex(MediaStore.Audio.Media._ID);
int iTitleCol = cSong.getColumnIndex(MediaStore.Audio.Media.TITLE);
int iArtistCol = cSong.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int iAlbumCol = cSong.getColumnIndex(MediaStore.Audio.Media.ALBUM);
int iDurationCol = cSong.getColumnIndex(MediaStore.Audio.Media.DURATION);
int iAlbumIDCol = cSong.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
int iDataCol = cSong.getColumnIndex(MediaStore.Audio.Media.DATA);

if (cSong != null && cSong.moveToFirst()) {
    do {
        String sArtist = cSong.getString(iArtistCol);
        String sAlbum = cSong.getString(iAlbumCol);

        if (sArtist.equals(MediaStore.UNKNOWN_STRING)) {
            sArtist = mContext.getResources().getString(R.string.UnknownArtist);
        }

        if (sAlbum.equals(MediaStore.UNKNOWN_STRING)) {
            sAlbum = mContext.getResources().getString(R.string.UnknownAlbum);
        }

        SongList.add(new Song(cSong.getLong(iIDCol), cSong.getLong(iAlbumIDCol), cSong.getString(iTitleCol), sArtist, sAlbum, cSong.getInt(iDurationCol), cSong.getString(iDataCol)));
    }
    while (cSong.moveToNext());
}

cSong.close();

#Selfie is displayed correctly because the Filename equals the Song-Title, but the others aren't displayed correctly!

EDIT:

I checked out that only non-MP3-Files cause problems! How can I fix this?

I hope you can help me!

Thanks!


Solution

  • I think problem is you have not set the projection argument for getContentResolver.query() method

    Try this

        ContentResolver musicResolver = getContentResolver();
    
        Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    
        Cursor cSong = musicResolver.query(musicUri,new String[]{MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media.DATA},null,null,null);