我试图查找导致这种情况的原因但是我无法找出原因发生的原因 - 我正在设置一个点击监听器以启用按钮切换功能。我没有收到任何错误弹出窗口,但是当我运行应用程序时它会崩溃并且logcat显示我在侦听器本身上获得了java.lang.NullPointerException。这是代码 -
public class MainScreen extends AppCompatActivity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
btn = (Button) findViewById(R.id.mainTypesBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainScreen.this, MainTypes.class));
}
});
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading_screen);
}
我在btn.setOnClickListener(new View.OnClickListener() {
MainTypes是第二个活动,并且没有任何内容。
答案 0 :(得分:3)
首先:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading_screen);
紧随其后:
@Override
protected void onCreate(Bundle savedInstanceState) {
然后你做:
btn = (Button) findViewById(R.id.mainTypesBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoadingScreen.this, MainTypes.class));
}
});
和第二个细节:
LoadingScreen 不是您当前的活动... MainScreen
答案 1 :(得分:2)
您在findViewById()
之前致电setContentView()
。试试这个:
@Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading_screen);
btn = (Button) findViewById(R.id.mainTypesBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoadingScreen.this, MainTypes.class));
}
});
}
答案 2 :(得分:1)
尝试这样的事情..
@Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading_screen);
btn = (Button) findViewById(R.id.mainTypesBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoadingScreen.this, MainTypes.class));
}
});
}
实际上setContentView
用你的按钮创建的setContentView
方法做了那个魔术。在此之前它只是空
答案 3 :(得分:1)
初始化按钮时,您的布局尚未设置。因此,首先需要设置布局,然后初始化可以解决问题的按钮。请尝试以下操作:`
@Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading_screen);
Button btn = (Button) findViewById(R.id.mainTypesBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoadingScreen.this, MainTypes.class));
}
});
}`