NullPointerException on button's OnClickListener

只愿长相守 提交于 2019-11-30 18:46:35
Blackbelt

The only reason why findViewById() would return null is because the View you are looking for does not belong to the current View. (The View you set with setContentView()). If R.id.buttonNewGame is in R.layout.startscreen, try to clean and rebuild your project.

It would seem that newGame is null. Do you have multiple layouts named startscreen.xml? A common cause of this exception would be creating buttonNewGame in one version but not the other; this would cause the code to build correctly but fail at runtime, exactly as you're describing, when the active layout failed to specify the button.

I see this error periodically, the trouble in my case is that android inpropertly maintaining same id's in different layouts. Make sure that your id's are unique not inside only one layout, but in entire application.

Set a break point on line 38 and launch the debugger. You're most likely trying to reference a button outside of the xml file R.layout.startscreen which would throw a NullPointerException.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!