3

I am trying to get the album art from the audio file Uri, here is my code:

// uri is the audio file uri

public static Bitmap getSongCoverArt(Context context, Uri uri){
    Bitmap songCoverArt = null;
    String[] projections = {MediaStore.Audio.Media.ALBUM_ID};
    Cursor cursor = null;
    try {
        cursor = context.getContentResolver().query(uri, projections, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
        cursor.moveToFirst();

        Uri songCover = Uri.parse("content://media/external/audio/albumart");
        Uri uriSongCover = ContentUris.withAppendedId(songCover, column_index);
        Log.d(TAG, uriSongCover.toString());
        ContentResolver res = context.getContentResolver();
        try {
            InputStream in = res.openInputStream(uriSongCover);
            songCoverArt = BitmapFactory.decodeStream(in);
        }catch (FileNotFoundException e){
            Log.e(TAG, e.getMessage());
        }
    }finally {
        if(cursor != null){
            cursor.close();
        }
    }

    return songCoverArt;
}

This function always returns "No entry for content://media/external/audio/albumart/0"

Neno0o
  • 133
  • 1
  • 10

1 Answers1

4

I think your problem lies in the appendId

   Uri songCover = Uri.parse("content://media/external/audio/albumart");
    Uri uriSongCover = ContentUris.withAppendedId(songCover, column_index)

replace column_index with Long _id of album rather than a column index which for _id is 0.

 album_id = c.getLong(c.getColumnIndex(MediaStore.Audio.Albums._ID));

where c is my cursor

Theo
  • 2,012
  • 1
  • 16
  • 29
  • I got an error, FATAL EXCEPTION: main java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent {dat=content://media/external/audio/media/4298 } android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 – Neno0o Oct 26 '14 at 19:59
  • Nenodo, if this resolved your issue, please accept as answer and vote up – Theo Oct 27 '14 at 18:09
  • @Theo where does `content://media/external/audio/albumart` come from and is this the same across all Android devices? – Vince VD Apr 17 '20 at 00:27
  • @Theo first i thought it was from `MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI` but that returns `content://media/external/audio/albums` and not `content://media/external/audio/albumart` – Vince VD Apr 17 '20 at 00:33
  • @Theo Is this reliable to use across all Android devices? Can't find anything in the docs about this hardcoded uri. – Vince VD Apr 27 '20 at 18:45