Home > Blockchain >  setOnClickListener does not work in android studio
setOnClickListener does not work in android studio

Time:06-14

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

CodePudding user response:

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

CodePudding user response:

    findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            findViewById(R.id.txt1).setText("finalyyyyyyyyyyy");
        }
    })
  • Related