-1

in my map i try to show hight quality markers, so i use xml markers from an svg files instead of using low png pictures, so to do that i convert the xml to bitmap with:

public BitmapDescriptor vectorToBitmap(Context context, @DrawableRes int id) 
{
    Drawable vectorDrawable = ContextCompat.getDrawable(context, id);
    int h = Objects.requireNonNull(vectorDrawable).getIntrinsicHeight();
    int w = Objects.requireNonNull(vectorDrawable).getIntrinsicWidth();
    vectorDrawable.setBounds(0, 0, w, h);
    Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bm);
    vectorDrawable.draw(canvas);
    BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bm);
    return bitmapDescriptor;
}

then i call this methode by:

BitmapDescriptor marker = vectorToBitmap(getActivity(),R.drawable.pin_work);

everything work fine in many devices, but sometimes i get this error

Context.getDrawable(int) on a null object reference

how can i fix this specially with LG smartphones?
thank you

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

0

First, you should use VectorDrawableCompat.create() instead of ContextCompat.getDrawable().

Here is an example of how to use VectorDrawableCompat.create()

   int iconResId = typedArray.getResourceId(R.styleable.MineRowView_mine_icon, 0);
    if (iconResId != 0) {
        Drawable icon = VectorDrawableCompat.create(typedArray.getResources(),iconResId, null);
        ivIcon.setImageDrawable(icon);
    }

In your case:

VectorDrawableCompat vectorDrawableCompat = VectorDrawableCompat.create(typedArray.getResources(),iconResId, null);
vectorDrawableCompat.draw(canvas);

Second, using Objects.requireNonNull(vectorDrawable) in this case is a bad practice because ContextCompat.getDrawable(context, id) annotates @Nullable which means that the return value of this method can be null, and requireNonNull will throw an exception. You should use requireNonNull only when you're sure that the object can't be null and it's not the case here.

OmB
  • 366
  • 2
  • 13