0

I use this code to get a Bitmap object from a bitmap image from drawable resources:

Bitmap avatar = ((BitmapDrawable) getDrawable(R.drawable.avatar_bpm)).getBitmap();

The code works but android studio suggests I use: Use ContextCompat.getDrawable()

What is it mean? And how do I convert my code to use the suggested version ?

cat15ets
  • 167
  • 10
  • That's rather roundabout, and creating an unnecessary `Drawable`. Use [`BitmapFactory.decodeResource()`](https://developer.android.com/reference/android/graphics/BitmapFactory#decodeResource(android.content.res.Resources,%20int)) instead to load the `Bitmap` directly. – Mike M. Aug 18 '21 at 16:58
  • ContextCompat.getDrawable( context, R.drawable.avatar_bpm). – Vaibhav Goyal Aug 18 '21 at 16:59
  • Mike, It's not. I use the bitmap object in a notification .setLargeIcon(avatar) and it requires a bitmap argument, if I use directly R.drawable.avatar_bpm it gives me an error (the resource is int type, that is what the error says). Vaibhav actually the full code if I use the hint is: ((BitmapDrawable) Objects.requireNonNull(ContextCompat.getDrawable(getApplicationContext(), R.drawable.avatar_bpm))).getBitmap() – cat15ets Aug 18 '21 at 17:44
  • Huh? This is what I suggested: `Bitmap avatar = BitmapFactory.decodeResource(getResources(), R.drawable.avatar_bpm);`. Doesn't matter where you're using the `Bitmap`. – Mike M. Aug 18 '21 at 17:48
  • 1
    Mike your solution works and I'm going to use it – cat15ets Aug 18 '21 at 18:19
  • Check this answer - https://stackoverflow.com/questions/3035692/how-to-convert-a-drawable-to-a-bitmap – Android Geek Aug 19 '21 at 05:05

0 Answers0