java.lang.NullPointerException 在 GetBitmap 上

java.lang.NullPointerException on GetBitmap

在我的地图中,我尝试显示高质量标记,所以我使用来自 svg 文件的 xml 标记而不是使用低 png 图片,为此我将 xml 转换为位图与:

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;
}

然后我通过以下方式调用此方法:

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

在许多设备上一切正常,但有时我会收到此错误

Context.getDrawable(int) on a null object reference

我如何用 LG 智能手机专门解决这个问题?
谢谢

首先,您应该使用 VectorDrawableCompat.create() 而不是 ContextCompat.getDrawable()。

这是一个如何使用 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);
    }

你的情况:

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

其次,在这种情况下使用 Objects.requireNonNull(vectorDrawable) 是一种不好的做法,因为 ContextCompat.getDrawable(context, id) 注解@Nullable 表示该方法的return 值可以为null,requireNonNull 会抛出异常。 只有当您确定对象不能为 null 时才应该使用 requireNonNull,而这里不是这种情况。