NullPointerException 使用位图时

NullPointerException When using Bitmaps

在 phone 上测试我的应用程序时,出现内存不足错误,经过一番研究,我发现这是由于我对位图的不当使用造成的。最初,我会这样声明位图:

Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.image_name);

从日志中,我看到错误源于此。因此,我四处阅读并尝试使用额外的参数选项,例如:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;

然后声明位图...

image = BitmapFactory.decodeResource(getResources(), R.drawable.image_name, options);

当 运行 出现这种情况时,我不再遇到内存不足错误,但在尝试使用位图时我确实收到空指针异常,如果它试图将它们绘制到我的 canvas,或对它们调用 .getWidth() 和 .getHeight()。

我很难解决这个问题,非常感谢您提供反馈。

错误日志:

01-27 18:47:42.597: E/AndroidRuntime(15698): java.lang.NullPointerException
01-27 18:47:42.597: E/AndroidRuntime(15698):    at android.graphics.Canvas.throwIfCannotDraw(Canvas.java:1083)
01-27 18:47:42.597: E/AndroidRuntime(15698):    at android.graphics.Canvas.drawBitmap(Canvas.java:1139)
01-27 18:47:42.597: E/AndroidRuntime(15698):    at com.mascal.petele.Game$OurView.drawMenu(Game.java:654)
01-27 18:47:42.597: E/AndroidRuntime(15698):    at com.mascal.petele.Looping.run(Looping.java:34)

在Game.java:654 处的代码行是:

c.drawBitmap(background, 0, 0, null);

这是第一次使用位图,以后也会出现这种情况。

这是 inJustDecodeBounds 的文档:http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inJustDecodeBounds

这是文字,突出显示我自己的:

If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.

如您所见,您设置了一个保证您将获得空位图的选项!

您的 background 变量设置为 null。也许它无法加载。先把它修好,让它指向一个Bitmap对象,然后你就可以画了。