andrey.shedko andrey.shedko - 3 months ago 17
Android Question

Android. NullReferenceException of Button

I'm new to Android development, so this is probably easy question.
There is Button defined in layout, but when Activity starting I see in debugger this Button is null. How this can happend?


<Button
android:id="@+id/show_answer_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/show_answer_button"/>


Activity:


private Button mShowAnswer;
mShowAnswer = (Button)findViewById(R.id.show_answer_button);
mShowAnswer.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
}
else {
mAnswerTextView.setText(R.string.false_button);
}
}
});

Answer

According to this comment setContentView() method is in wrong place, it's must be place before binding button variable and button xml view.

setContentView(R.layout.your_xml_layout_name);
private Button mShowAnswer;
mShowAnswer = (Button)findViewById(R.id.show_answer_button);
Comments