2011-08-21 87 views
8

你好我正在寫一個小的Android應用程序(版本2.3.3)。現在我在這個非常基本的代碼得到這個奇怪的空指針異常:使用在主menu.xml文件的那一刻在使用findViewById時onCreate()中的NullPointerException - 之前使用了setContentView?

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

newDeck = (Button) findViewById(R.id.newDeckB); 
loadDeck = (Button) findViewById(R.id.loadDeckB); 
viewEdition = (Button) findViewById(R.id.viewEditionB); 

newDeck.setOnClickListener(this); 
loadDeck.setOnClickListener(this); 
viewEdition.setOnClickListener(this); 
} 

林這個簡單的佈局:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 
<Button android:id="@+id/newDeckB" 
     android:text="New Deck" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 
<Button android:id="@+id/loadDeckB" 
     android:text="Load Deck" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 
<Button android:id="@+id/viewEditionB" 
     android:text="View Edition" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 
<TextView android:id="@+id/currentDeckTextView" 
     android:text="Default Deck" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"/> 
</LinearLayout> 

現在我的問題是線25 nullpointexception ,這是我設置第一個clickListener的線

newDeck.setOnClickListener(this); 

使用調試器我發現按鈕newDeck爲空。我在網上搜索了很多,但這類問題的唯一答案是檢查setContentView是否在findViewById之前設置。這顯然是這種情況。

我會很樂意提供任何建議。

Thx in Before!

+0

是否'R.id.newDeckB'實際上在'R.layout.mainmenu'存在嗎? –

+0

我遇到了完全相同的問題(令人沮喪!),下面的評論(@manelizzard)爲我解決了這個問題:'有時你需要「清理」並重建項目以獲得正確的重新編譯,這是來自Eclipse'。 (即你不需要使用'onPostCreate()'!) – coco

+0

清理和重建工程...多麼奇怪。 –

回答

10

獲取您的視圖並在onPostCreate()方法中設置偵聽器。

+0

Thx很多爲您的帖子。 我不明白爲什麼,但現在它工作。 我只是改變了在Java代碼和XML(從newDeckB到​​newDeckButton)中的ID名稱,現在它的工作原理。我真的不明白,因爲我昨天已經嘗試過,並沒有解決問題。 – Neuhier

+1

有時您需要「清理」並重建項目以獲得編譯的正確的resurces,這是來自Eclipse的東西。 onPostCreate()方法在內容完全加載時執行。接受答案,PLZ =) – manelizzard

+0

謝謝你的解釋。 – Neuhier

-2

有跡象表明,在App預計,的onCreate()兩個事件,並且在onStart()

哪一個你把這個功能,事務。

我不得不從的onCreate()移動 「findViewByID」,以在onStart()

@Override 
protected void onStart() { 
     // use findViewById() here instead of in onCreate() 
    } 
+1

請包括更多信息。 –

+0

你需要更清楚地解釋你的答案。否則,即使它是正確的,它也不是很有用。 – JakeGould

+0

App有兩個事件,onCreate()和onStart() 你把這個函數放在哪一個,很重要。 –

相關問題