且构网

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

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

更新时间:2022-11-22 16:11:48

您需要在onCreate内实例化视图,并在setContentView之后,直到通过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());
    }
});

}