2011-08-21 34 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() 你把这个函数放在哪一个,很重要。 –

相关问题