4

I try to set the Tag with the ID of one of my buttons:

     int boeserzufall = (int) (Math.random()*23);
     Button boese = arr.get(boeserzufall);
     boese.setBackgroundResource(R.drawable.williboese);
     boese.setTag(R.drawable.williboese);

That works fine, boese.getTag() brings me the correct id. arr is an ArrayList<Button> that contains all my buttons.

Now in my OnClick() method I want to check if the current button has the same resId as boese

    b5.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            count++;
            int resId = (Integer) arg0.getTag();
            if(resId == R.drawable.williboese) {
                Toast.makeText(MainActivity.this, "heeeee", Toast.LENGTH_SHORT).show();
            }

        }
    });

My problem is that I get a Nullpointer Exception when I try read arg0.getTag()

Edit:

First, I take a random button out of my array and therefor I want to set the background image with R.drawable.williboese. So on one of my 25 buttons I have a different background image than on the others. This one I have to find and react different than on the others...

user896692
  • 2,351
  • 7
  • 36
  • 57

2 Answers2

1

If the button does not have a tag, you will get a NPE when your code tries to unbox the tag to an int. If you're sure that the only tags are Integer objects, you can try this instead:

b5.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        count++;
        Integer resId = (Integer) arg0.getTag();
        if(resId != null && resId == R.drawable.williboese) {
            Toast.makeText(MainActivity.this, "heeeee", Toast.LENGTH_SHORT).show();
        }

    }
});

If there's a chance that a tag might exist and be something other than an Integer, then you should also guard against a ClassCastException (or declare resId to be an Object and replace resId != null with resId instanceof Integer and do the cast only if it passes.

Looking at your overall logic, however, you might find View.findViewWithTag(Object) to be a useful method that would allow you to bypass the testing.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

According to your last edit, you set a tag only on one specific button, out of 25. This is an int autoboxed into an Integer. You do not even need the value of the tag, because this is non-null only on that specific button. This should do:

public void onClick(View view) {
    count++;
    if(view.getTag() != null) {
        Toast.makeText(MainActivity.this, "heeeee", Toast.LENGTH_SHORT).show();
    }
}
Gil Vegliach
  • 3,542
  • 2
  • 25
  • 37