Search code examples
androidandroid-studioandroid-mediaplayerandroid-cursorandroid-music-player

Album art for song is not showing correct in android


Here is my cursor by which I m getting songs from local storage :

cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,MediaStore.Audio.AudioColumns.DURATION+">0", null, sortOrder);

I m displaying album by using another cursor like this shown below because I m not able to do this using same cursor :

ContentResolver musicResolve = getContentResolver();
Uri smusicUri = android.provider.MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;    
Cursor musicCursorTogetAlbum =musicResolve.query(smusicUri,null, null, null, null);

I m displaying album like this but it doesn't display correctly :

    musicCursorTogetAlbum.moveToFirst();
    musicCursorTogetAlbum.move(cursorPosition);

    int x = musicCursorTogetAlbum.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
    int id_albumCursor = musicCursorTogetAlbum.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);

    String thisArt = musicCursorTogetAlbum.getString(x);

    Bitmap bm = BitmapFactory.decodeFile(thisArt);
    Bitmap bm_temp = BitmapFactory.decodeFile(thisArt);

    Drawable dr = new BitmapDrawable(getResources(), bm);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {  
         iv_album_art.setImageBitmap(bm);
    }

And cursorPosition is the int type variable which gives position of cursor of cursor which I m using for getting song from local storage.


Solution

  • You can use this method to get album art of songs :

    `

    public static Bitmap getAlbumart(Context context, Long album_id){
        Bitmap bm = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        try{
              final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
              Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
              ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
              if (pfd != null){
                  FileDescriptor fd = pfd.getFileDescriptor();
                  bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
                  pfd = null;
                  fd = null;
              }
          } catch(Error ee){}
          catch (Exception e) {}
          return bm;
        }
    

    `