Android ImageView NullPointerException

I have two images: red light and green light. I have my own ListView, which I would like to display red light when the list item is inactive, and green light when it is active. The list item is activated when clicked.

Here is my code

row.xml

<ImageView android:id="@+id/iconLight" android:src="@drawable/light_off" android:layout_width="wrap_content" android:layout_height="wrap_content"/> 

main.java

 ImageView iconLight = (ImageView)findViewById(R.id.iconLight); iconLight.setImageResource(R.drawable.light_on); 

I get a NullPointerException throwing a string specifying an image resource. So I did a little testing, I deleted the line specifying src in the XML file, and just tried installing it in the main class. Another NPE. Therefore, I tried not to change the resource, but simply changed the alpha. Another NPE.

I'm not sure what I'm doing wrong. The files light_off.png and light_on.png are in res/drawable-ldpi , and each of them works when I specify them in XML. But any change that I try to make in iconLight in the main file causes this NPE. Any ideas?

+4
source share
2 answers

The only way to get NPE in a string ...

 iconLight.setImageResource(R.drawable.light_on); 

Whether the iconLight parameter is null. So your findViewById is not working. Have you set your layout before calling findViewById? Are you sure that R.id.iconLight is in the activity management layout?

+12
source

I had the same problem. Here is the code that helped me understand. This is for a dialog box, but may help you.

  final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.custom); dialog.setTitle("Title..."); TextView text = (TextView) dialog.findViewById(R.id.text); text.setText("Android"); ImageView image = (ImageView) dialog.findViewById(R.id.image); image.setImageResource(R.drawable.ic_launcher); 

Keep track of the line to the last. Notice how it creates an instance of ImageView. In any case, every change to the image is done after setContentView.

0
source

All Articles