Zaid Sh
Zaid Sh

Reputation: 11

setOnClickListener does not work in android studio

that is my code, very simple and basic public Button btn1; public TextView txt1;

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

    findViewById(R.id.txt1);
    findViewById(R.id.btn1);

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            txt1.setText("finalyyyyyyyyyyy");


        }
    });

and the error showing is: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Upvotes: 0

Views: 874

Answers (2)

Janki
Janki

Reputation: 91

Save the element in variable and set onClick method to that particular variable as below:

btn1 = findViewById(R.id.btn1);

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            txt1.setText("finalyyyyyyyyyyy");


        }
    });

Upvotes: 0

Mirco0
Mirco0

Reputation: 321

The problem is here

findViewById(R.id.txt1);
findViewById(R.id.btn1);

you are getting the views from the .xml file but you are not actually assigning the value to any object... so when you try to call a method to the btn1 it's null (empty) and throws an error

So just assign the value you are getting to the views objects like so:

txt1 = findViewById(R.id.txt1);
btn1 = findViewById(R.id.btn1);

This will fix the problem

Upvotes: 1

Related Questions