Android ImageView NullPointerException

2019-06-24 06:13发布

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?

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-24 07:04

I had the same problem. Here is a code that helped me understand. It is for a Dialog window but might help you too.

    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);

Watch the line before the last one. Notice how it instantiates the ImageView. Anyway every change to the image is made after the setContentView.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-24 07:08

The only way to get a NPE in the line...

iconLight.setImageResource(R.drawable.light_on);

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?

查看更多
登录 后发表回答