且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android Activity -- NullPointerException(“无法实例化活动 ComponentInfo")?

更新时间:2022-11-22 15:59:06

您需要在 onCreate 中实例化您的视图,并且在 setContentView 之后,Activity 不知道您指的是哪些视图,直到您通过 setContentView 设置了活动布局方法.如果这不能解决问题,那么如果您从 LogCat 发布堆栈跟踪以便知道确切的行号,将会有所帮助.

You need to instantiate your views inside onCreate and after the setContentView, the Activity doesn't know which views you are referring until you set the Activities layout via the setContentView method. If this doesn't fix the problem it would help if you posted the stack trace from LogCat so the exact line number is known.

@Override

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.main);


TextView tv = (TextView) findViewById(R.id.textView1);
EditText et = (EditText) findViewById(R.id.edittext);

Button b = (Button) findViewById(R.id.Enter);

b.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        tv.setText(et.getText().toString());
    }
});

}