我的問題是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