android createBitmap NullPointerException

时间:2012-01-17 22:55:04

标签: android nullpointerexception

当我尝试调用createBitmap时,我得到了一个java.lang.NullPointerException。这是我的代码:

board = Bitmap.createBitmap(handler.signs.length * cellSize, 
        handler.signs[0].length * cellSize, Bitmap.Config.ARGB_8888);

其中宽度和高度也大于零。这是堆栈跟踪:

java.lang.NullPointerException
at android.graphics.Bitmap.createBitmap(Bitmap.java:478)
at org.me.five_stones_project.game.GameView.drawBoard(GameView.java:334)
at org.me.five_stones_project.game.GameView.increaseBoard(GameView.java:293)
at org.me.five_stones_project.game.GameHandler.checkStatus(GameHandler.java:304)
at org.me.five_stones_project.game.GameHandler.makeMyStep(GameHandler.java:211)
at org.me.five_stones_project.game.GameView.onTouchEvent(GameView.java:238)
at android.view.View.dispatchTouchEvent(View.java:3891)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1719)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1150)
at android.app.Activity.dispatchTouchEvent(Activity.java:2102)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1703)
at android.view.ViewRoot.deliverPointerEvent(ViewRoot.java:2200)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1884)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:861)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:619)
at dalvik.system.NativeStart.main(Native Method)

我看了一下Bitmap的源代码,发现了这个:

476         public static Bitmap createBitmap(int width, int height, Config config) {
477         Bitmap bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true);
478         bm.eraseColor(0);    // start with black/transparent pixels
479         return bm;
480     }

那么当调用 bm.eraseColor(0)时会发生异常吗?

有人能帮助我吗?谢谢!

2 个答案:

答案 0 :(得分:5)

我跟踪了几个间歇性错误,其中Bitmap.createBitmap()返回null;他们主要发生在中国Android手机上。传递的参数没问题,但我发现只要发生这种情况,jvm的内存就非常低。

我的理论是有些情况下createBitmap()会耗尽内存并返回null而不是抛出OutOfMemoryException(这通常就是这样)。

我的“修复”是检查createBitmap()是否返回null并抛出我们自己的OutOfMemoryException,以便正确分类。然后我们的错误记录将其视为设备问题而不是功能错误。

答案 1 :(得分:1)

尝试使用createScaledBitmap,我之前遇到同样的问题,我记得的原因是 所需的位图宽度或高度超过了设备的大小。

希望这会对你有所帮助。