容易丢失一些东西(按钮 OnClick 导致空指针)
突然我的按钮导致空指针异常。我没有更改此活动类中的任何代码。周末的大部分时间我都在努力确定这一点。我在模拟器和设备上都遇到空指针异常。
这是一个带有按钮的简单屏幕。我可以轻松地废弃它并编写新代码,但想知道是什么导致了这个问题。如果没有,我将编写新代码。
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Button b1 = (Button) findViewById(R.id.MainActBtn);
b1.setOnClickListener(new View.OnClickListener() { //Error is here
public void onClick(View v) {
Intent intent = new Intent(StartScreen.this, MainActivity.class);
startActivity(intent);
}
});
有什么帮助吗?
Suddenly my buttons cause null pointer exceptions. I have not changed any code in this activity class. I have been up most of the weekend trying to pin this down. I get null pointer exceptions in both the emulator and on device.
This is a simple screen with buttons. I could easily scrap this and write new code, but would like to know what has caused this issue. If not, I will just write new code.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Button b1 = (Button) findViewById(R.id.MainActBtn);
b1.setOnClickListener(new View.OnClickListener() { //Error is here
public void onClick(View v) {
Intent intent = new Intent(StartScreen.this, MainActivity.class);
startActivity(intent);
}
});
Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试重新清理并构建您的项目。我过去也遇到过这个错误,是由于更改了
R.class
Resource 类引起的,但是 using 类中的静态引用没有被增量 java 编译器正确替换,因此资源没有发现时间更长。Try a fresh clean and build of your project. I got this error too in the past, caused by a changed
R.class
Resource class, but the static references in the using classes weren't properly replaced by the incremental java compiler, so the resources are no longer found.我认为您不会因为单击按钮而出现空指针异常,只是因为按钮的声明。
您可以在编写 onClickListener 之前进行检查。
问题可能是在设置 XML 视图或同时检查您正在使用的按钮是在您在 setContentView 中使用的同一 xml 中定义的。
在这一切之后,还要清理并构建您的项目。
I think You are not getting Null Pointer Exception because of the Button click just because of the declaration of the button..
You can check before writting the onClickListener..
The Problem is may be in setting the XML view or also check the button you are using is defined in the same xml you are using in setContentView.
After this all, also Clean and Build your project.