我的问题是imageView将在showPicture()
为空。我从另一个线程调用这个方法。 如果我删除if (imageView != null)
...条件,我会得到一个NullPointerException
。你能告诉我为什么?谢谢。Android:findViewById NullpointerException
活动的java文件:
public class ClientActivity extends Activity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.client);
imageView = (ImageView) findViewById(R.id.image);
imageView.setImageResource(R.drawable.p1); //IT WORKS
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.client, menu);
return true;
}
public void showPicture(final int ID) {
if (imageView != null) {
imageView.post(new Runnable() {
@Override
public void run() {
imageView.setImageResource(ID);
}
});
} else { // It will be executed.
System.out.println("WHY imageView IS NULL?!");
}
}
布局xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/image"
android:contentDescription="@string/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/bg" />
</LinearLayout>
中的strings.xml:
<string name="content">image</string>
你在哪里叫'showPicture(......)'? –
它取决于你如何调用'showPicture()'? – user370305
可能你用'new'来自己实例化活动。不要这样做。 – laalto