2013-03-04 86 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