I have two images, a red light and a green light. I have a custom ListView that I would like to display a red light when a list item is inactive, and a green light when it is active. A list item is activated when it is pressed.
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 executing the line that sets the image resource. So I did a little testing, I deleted the line setting the src in the XML file and just tried to set it in the main class. Still a NPE. So I tried not changing the resource, but just changing the alpha. Still NPE.
I’m not sure what I’m doing wrong. The files light_off.png and light_on.png are both in res/drawable-ldpi and either of them work when I specify them in the XML. But any change I attempt to make to iconLight in the main file causes this NPE. Any ideas?
The only way to get a NPE in the line…
Is for iconLight to be null. So, your findViewById is failing. Have you set your layout before you call findViewById? Are you sure R.id.iconLight is in the Activity’s root layout?