0

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);
                }
            }
        });
10
  • 2
    Have you called setContentView() before the above code. Also, make sure you reference the correct layout file. Commented Aug 31, 2016 at 4:26
  • check your TextView is correctly initialized or not Commented Aug 31, 2016 at 4:27
  • @Shaishav, no, setContentView() certainly called after this. Commented Aug 31, 2016 at 4:30
  • @VishalThakkar, according his post he can compile and run the app, your idea does not correct. Commented Aug 31, 2016 at 4:31
  • 1
    @andrey.shedko, you must call setContentView() before any view binding in your activity Commented Aug 31, 2016 at 4:32

2 Answers 2

1

try this:

 private Button mShowAnswer;

         @Override
            protected void onCreate(Bundle savedInstanceState) {
                try {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_login);

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

            }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.