2012-01-24 93 views
-1

在我的應用程序的第一個活動的onCreate的相關部分:爲什麼findViewById返回null?

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    GridView sdcardImages = (GridView) findViewById(R.id.sdcard); 
    sdcardImages.setAdapter(new ImageAdapter(this)); 

    // ... 

} 

佈局/ main.xml中:

<?xml version="1.0" encoding="utf-8"?> 
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/sdcard" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:padding="2dp" 
    android:verticalSpacing="2dp" 
    android:horizontalSpacing="2dp" 
    android:numColumns="auto_fit" 
    android:columnWidth="70dp" 
    android:stretchMode="columnWidth" 
    android:gravity="center" 
/> 

在這裏有沒有問題,然後突然儘管甚至沒有觸及此代碼的任何最近我開始在sdcardImages.setAdapter(new ImageAdapter(this));findViewById(R.id.sdcard)上突然返回NullPointerException異常。

任何人都知道爲什麼會發生這種情況?清理和重建項目並沒有幫助。

編輯:解決我猜,我第一次清理它沒有任何改變,但我清理它後第二次工作。

+0

不,並且這樣做沒有幫助 – herpderp

+0

不,我以前沒有導入它。 – herpderp

回答

0

適配器需要一個遊標。傳遞一個有效的光標,它應該工作。

+0

否則我在這裏看不到任何錯誤的代碼片段。如果視圖是您的ContentView的一部分,您應該能夠爲findviewbyid獲取正確的ID。 –

+0

它確實有一個,這只是我在問題中省略的 – herpderp