Android Activity — NullPointerException (“unable to instantiate activity ComponentInfo”)?

和自甴很熟 提交于 2019-12-03 21:31:25
mmaitlen

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());
    }
});

}

I assume that the problem is caused by the two fields tv and et which you initialize directly when the class instance is created.

You should move the initialization of both fields in the onCreate method as you have done it with "Button b".

Before setting the content you are trying to instantiate the textview and EditText that's why you got null pointer exception
Thanks

Null pointer exception means that you are referencing something that isn't yet created.
setContentView creates the fields neccesary by the variables tv and et.
So, you need to have tv and et after the setContentView.

yeah, additional of above answers, i give that error because define a variable before onCreate method:

boolean in = true;

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