Android:findViewById NullpointerException

时间:2014-04-28 08:57:12

标签: java android nullpointerexception imageview

我的问题是showPicture()中的imageView将为空。我从另一个线程调用此方法。 如果我删除 if (imageView != null) ...条件,我将获得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>

2 个答案:

答案 0 :(得分:0)

尝试以下代码: -

    setContentView(R.layout.client);
    imageView = (ImageView) findViewById(R.id.image);
    imageView.setImageResource(R.drawable.p1);

    //after this use function show picture
    showPicture(id);

您必须在setContentView后调用您的函数,因为在setContentView layout content initialize.之后

答案 1 :(得分:0)

  

我的程序管理基于套接字的通信。当客户端连接到服务器套接字时,将启动此ClientActivity:clientActivity = new ClientActivity(); Intent intent = new Intent(mainActivity,clientActivity.getClass());

永远不要使用new实例化活动。这些类不应该是首先出现的活动,要么应该使用Intent来调用它们。

NPE的原因是您自己创建的活动没有调用onCreate()