[英]Android bitmap sometimes returning null
I am making a brick-breaker game for android and attempting to change the image of the background. 我正在为Android制作一款破砖游戏,并尝试更改背景图像。 On the first run of the game this works 100% of the time.
在游戏的第一次运行中,这种方法在100%的时间内有效。
mBackgroundImage = BitmapFactory.decodeResource
(gameView.getContext().getResources(),
R.drawable.planet3);
planet3 is in the res/drawable folder. planet3在res / drawable文件夹中。
If i return to the previous screen and start a new game, I get a NPE roughly 90% of the time. 如果返回上一个屏幕并开始新游戏,大约90%的时间我会获得NPE。 if I use a resource that was provided with the framework i am working on which is in the same folder as "planet3", Strangely it works 100% of the time regardless of whether its a new game or the first game etc.
如果我使用与我一起工作的框架一起提供的资源,并且该资源与“ planet3”位于同一文件夹中,那么奇怪的是,无论是新游戏还是第一个游戏,它都可以100%地工作。
Why could this be happening some of the time and not others. 为什么在某些时间而不是其他时间会发生这种情况。 I generally find that when it does work it is because i am debugging it and stepping through line by line, however this could just be coincidence.
我通常会发现它确实起作用时是因为我正在调试它并逐行进行调试,但是这可能只是巧合。
The code i have at the moment is as follows, TheGame is the current Thread the game is running on, the code i pasted above is in the constructor of this, IE everytime a new game is made, the background should be set. 我目前的代码如下,TheGame是游戏正在运行的当前线程,我上面粘贴的代码在此构造函数中,IE每次制作新游戏时都应设置背景。 you can also see the file structure on the left to verify that the file "background" is in the same folder as the "planet3":
您还可以在左侧看到文件结构,以验证文件“ background”是否与“ planet3”位于同一文件夹中:
as far as the error is concerned i don't have an actual error message as it just says that MOOC has stopped working, and then restarts the program. 就错误而言,我没有实际的错误消息,只是说MOOC已停止工作,然后重新启动程序。
如果您使用沉重的图像,可能会发生这种情况,或者请在此处发布所有代码以及异常,以获取更好的分辨率
I think that the reason for NPE in your case is : 我认为您遇到NPE的原因是:
The BitmapFactory is unable to find the context parameter gameView.getContext() BitmapFactory无法找到上下文参数gameView.getContext()
You should use : 您应该使用:
mBackgroundImage = BitmapFactory.decodeResource
(getApplicationContext().getResources(),
R.drawable.planet3);
If you have saved context in member variable ie mContext through constructor then you can use that : 如果您已经通过构造函数将上下文保存在成员变量(即mContext)中 ,则可以使用该上下文:
mBackgroundImage = BitmapFactory.decodeResource
(mContext.getResources(),
R.drawable.planet3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.