Getting a Nullpointer at view.getTag

北城以北 提交于 2019-12-10 16:13:19

问题


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...


回答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();
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/21314110/getting-a-nullpointer-at-view-gettag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!