Android NullPointerException on getColor()



  • taskList.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View view,
                                            int position, long id) {
                        TextView item = (TextView) view;
                        ColorDrawable cd = (ColorDrawable) item.getBackground();
                        int colorCode = cd.getColor();
                        if(colorCode == R.color.colorGray){
                            item.setBackgroundResource(R.color.colorRed);
                        }
                    }
                }
        );
    

    It's the NullPointerException. I need every element of ListView to change color three times.

    12-15 20:04:40.061 23361-23361/com.igorexz.colortasks E/AndroidRuntime: java.lang.NullPointerException 12-15 20:04:40.061 23361-23361/com.igorexz.colortasks E/AndroidRuntime
    

    at com.igorexz.colortasks.MainActivity$1.onItemClick(MainActivity.java:42)



  • First, the problem may be that you give a view of color and try to drawable.

    We need to create xml drawable and pour it into the right color.

    The drawable should be used as a background to your view.

    We need to change the color code:

    if(colorCode == getResources.getColor(R.color.colorGray, getTheme)){
       item.setBackgroundResource(R.drawable.red_drawable);
    }
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2