2014-04-28 43 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.