2014-04-28 48 views
-2

我的问题是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> 
+0

你在哪里叫'showPicture(......)'? –

+0

它取决于你如何调用'showPicture()'? – user370305

+0

可能你用'new'来自己实例化活动。不要这样做。 – laalto

回答

0

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

永远不要用new实例化活动。要么这些课程不应该是第一个活动,或者你应该用Intent来调用它们。

NPE的原因是onCreate()未在您自己创建的活动上调用。

+0

现在我明白是什么导致了错误。我修改了我的代码,它工作。 谢谢! – Lyra

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.