2013-03-04 80 views
3

我有一个问题,我似乎无法解决!我正在开发一个简单的安卓游戏,几乎实现了一切,但后来决定添加一些障碍(游戏是一个月球着陆器风格的游戏)。Android空指针onDraw位图图片

基本上,我创建了一个Asteroid类,只是试图在屏幕上绘制它们。当加载游戏的小行星被吸引,和一切工作正常,但如果您按下home键或关闭电源,然后重新启动游戏,我收到了NPE:

03-04 21:33:21.243: E/AndroidRuntime(10748): FATAL EXCEPTION: Thread-680 
03-04 21:33:21.243: E/AndroidRuntime(10748): java.lang.NullPointerException 
03-04 21:33:21.243: E/AndroidRuntime(10748): at com.swiss196.LunarLander.GameThread.doDraw(GameThread.java:421) 
03-04 21:33:21.243: E/AndroidRuntime(10748): at com.swiss196.LunarLander.GameThread.run(GameThread.java:386) 

并将其指向下面的代码:

canvas.drawBitmap(test2.getBitmap(), 120, 120, null); 

这将建议帆布或getBitmap返回的test2对象/图像为null,但在此之前,我检查画布不为空。并在位图内,我检查图像不为零:

public Bitmap getBitmap() { 
if(asteroidImage == null) 
    asteroidImage = BitmapFactory.decodeResource(mGameView.getContext().getResources(), 
               R.drawable.asteroid); 

return asteroidImage; 
} 

有什么想法?

+4

如果decodeResource返回null(它会出错),getBitmap函数返回null。检查可能性。 – 2013-03-04 21:40:58

回答

1

我忘记重新加载一些来自包,包括图像所需的变量..

感谢人你的帮助!

0

您可能超出了您的内存预算,这就是您尝试decode your Bitmap时得到空值的原因。

开发者网站有pretty good descriptions如何避免这种情况。

一个重要的选项使用(再来看第二个链接的例子如何使用它)是“BitmapFactory.Options”,让您只是为了验证,如果你有足够的内存,为你的位图:

BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inJustDecodeBounds = true; 
BitmapFactory.decodeResource(getResources(), R.id.myimage, options); 
int imageHeight = options.outHeight; 
int imageWidth = options.outWidth; 

引用文档

Setting the inJustDecodeBounds property to true while decoding avoids memory allocation, returning null for the bitmap object but setting outWidth, outHeight and outMimeType. This technique allows you to read the dimensions and type of the image data prior to construction (and memory allocation) of the bitmap.

+0

当然,我会得到一个'java.lang.OutofMemoryError:位图大小超过虚拟机预算.'错误? – swiss196 2013-03-04 22:55:29

+0

不幸的是,没有。阅读文档(这里:http://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeResource(android.content.res.Resources,int))。 – DigCamara 2013-03-04 23:00:55

+0

你得到了什么(如果你在logcat中查找它)是错误信息。不过,您不会收到可捕获的异常。 – DigCamara 2013-03-04 23:05:16