GetBitmap上的java.lang.NullPointerException

时间:2018-10-14 08:39:00

标签: android nullpointerexception maps marker

在我的地图中,我尝试显示高质量的标记,因此我使用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智能手机专门解决此问题?
谢谢

1 个答案:

答案 0 :(得分:0)

首先,您应该使用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);
    }

其次,在这种情况下使用Objects.requireNonNull(vectorDrawable)是一个不好的做法,因为 ContextCompat.getDrawable(context,id)注释@Nullable,这意味着此方法的返回值可以为null,并且requireNonNull将引发异常。 仅在确定对象不能为null且此处不是这种情况时,才应使用requireNonNull。