【问题标题】:java.lang.NullPointerException on GetBitmap [duplicate]GetBitmap 上的 java.lang.NullPointerException [重复]
【发布时间】:2018-10-14 08:39:00
【问题描述】:

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

【问题讨论】:

    标签: android nullpointerexception maps marker


    【解决方案1】:

    首先,您应该使用 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,表示该方法的返回值可以为null,requireNonNull会抛出异常。 仅当您确定对象不能为空且此处并非如此时,才应使用 requireNonNull。

    【讨论】:

      猜你喜欢
      • 2018-12-11
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      相关资源
      最近更新 更多