Android ImageView NullPointerException

谁都会走 提交于 2019-12-13 13:27:08

问题


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?


回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/4393976/android-imageview-nullpointerexception

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