0

I initialised a button with

Button button1 = null;

in the beginning of my activity. After the layout is set, I do

final   Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(this);

The onClick looks like that

public void onClick(View v) {
        if(v == button1) {System.out.println("asd");};
        System.out.println(v);
    }

The print shows "I/System.out(22758): android.widget.Button@**405632f0**" and of course, the println("asd") doesn't show up.

I don't want to get the Button@** code for every single button because working with the id of course is much easier.

Someone has in Idea what I did wrong?

user2161301
  • 674
  • 9
  • 22

4 Answers4

2

instead of this

public void onClick(View v) {
        if(v == button1) {System.out.println("asd");};
        System.out.println(v);
    }

use this

public void onClick(View v) {
        if(v.getId() == R.id.button1) {System.out.println("asd");};
        System.out.println(v);
    }

WHY??

because when you are comparing using '==' the it is comparing two objects wheter it is the same reference. that i checks whether both object refers to the same memory.

To solve this you can check their id which is easily comparable.

stinepike
  • 54,068
  • 14
  • 92
  • 112
1

R.id.button1 is actually an Integer in R.java, it's not a String or anything else that can be truncated to button1. Instead use:

if(v.getId() == R.id.button1)

Also in Java you cannot use == to test equality on non-primitive objects, you must use equals(). Read about the difference in How do I compare strings in Java?

Community
  • 1
  • 1
Sam
  • 86,580
  • 20
  • 181
  • 179
  • Thank you guys, all of the solution worked. I will mark all as answer. Silly me. And thanks for the advice that v.getId() is better, will use that in future. Have a nice day – user2161301 Apr 17 '13 at 14:52
1

button1 is null. So you compare null and not null. change this:

final   Button button1 = (Button) findViewById(R.id.button1);

to:

button1 = (Button) findViewById(R.id.button1);

and it will work. But you better compare R.id.button1 and v.getId() numbers. Not views itself.

Leonidos
  • 10,482
  • 2
  • 28
  • 37
  • Thank you guys, all of the solution worked. I will mark all as answer. Silly me. And thanks for the advice that v.getId() is better, will use that in future. Have a nice day – user2161301 Apr 17 '13 at 14:51
1

as @Leonidos said, change:

final   Button button1 = (Button) findViewById(R.id.button1);

to:

button1 = (Button) findViewById(R.id.button1);

and, yes, you can compare references: if you see android sources there are two strategies: some people compare reverences like:

if (v == mSomeButton) {

and some use id like:

if (v.getId() == R.id.some_button) {
pskink
  • 23,874
  • 6
  • 66
  • 77