你好我正在寫一個小的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!
是否'R.id.newDeckB'實際上在'R.layout.mainmenu'存在嗎? –
我遇到了完全相同的問題(令人沮喪!),下面的評論(@manelizzard)爲我解決了這個問題:'有時你需要「清理」並重建項目以獲得正確的重新編譯,這是來自Eclipse'。 (即你不需要使用'onPostCreate()'!) – coco
清理和重建工程...多麼奇怪。 –