2012-01-24 65 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