Search code examples
javaandroidandroid-music-player

Get cover of the songs in mediastore


I'm trying to get a Cover (album art) of the song using the following code:

public static String getCoverArtPath(Context context, long androidAlbumId) {
    String path = null;
    Cursor c = context.getContentResolver().query(
            MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
            new String[]{MediaStore.Audio.Albums.ALBUM_ART},
            MediaStore.Audio.Albums._ID + "=?",
            new String[]{Long.toString(androidAlbumId)},
            null);
    if (c != null) {
        if (c.moveToFirst()) {
            path = c.getString(0);
        }
        c.close();
    }
    return path;
}

This method returns a string of an image path but this path points to a non-formatted file. How to set this image on the ImageView? If you know of any other way than this method please tell me.


Solution

  • You can create a drawable from the path and set it

    Drawable drawable = Drawable.createFromPath(path_of_the_cover_art);
    yourImageView.setImageDrawable(drawable);
    

    Or create a file:

    File image = new  File(path_of_the_cover_art);
    if(image.exists()){
        Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath());
        yourImageView.setImageBitmap(bitmap);
    }
    

    just make sure you have the WRITE_STORAGE_PERMISSION for that!