Android 使用findViewById时onCreate()中的NullPointerException-以前是否使用过setContentView?

Android 使用findViewById时onCreate()中的NullPointerException-以前是否使用过setContentView?,android,Android,您好,我正在编写一个Android应用程序(版本2.3.3)。现在我在这段非常基本的代码中得到了一个奇怪的空指针异常: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mainmenu); newDeck = (Button) findViewById(R.id.newDeckB); loadDeck = (Button)

您好,我正在编写一个Android应用程序(版本2.3.3)。现在我在这段非常基本的代码中得到了一个奇怪的空指针异常:

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);
}
我现在在main menu.xml中使用这个简单的布局:

<?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>
使用调试器,我发现按钮newDeck为null。我在网上搜索了很多,但解决这类问题的唯一办法是检查setContentView是否设置在findViewById之前。这里显然就是这样

我很乐意接受任何建议


Thx在前面

获取视图并在onPostCreate()方法中设置侦听器。

应用程序需要两个事件:onCreate()和onStart()

你把这个函数放在哪一个很重要

我不得不将“findViewByID”从onCreate()移动到onStart()


R.id.newDeckB
确实存在于
R.layout.main菜单中吗?
?我遇到了完全相同的问题(令人沮丧!),下面的评论(@manelizzard)帮我解决了这个问题:“有时候你需要“清理”并重新构建项目以获得正确的resurces编译,这是来自Eclipse的。”。(即,您不需要使用
onPostCreate()
!)清理和重建工作。。。真奇怪。谢谢你的帖子。我真的不明白为什么,但现在它起作用了。我刚刚更改了java代码和xml中的id名称(从newDeckB到newDeckButton),现在它可以工作了。我真的不明白,因为我昨天已经试过了,但它并没有解决问题。有时你需要“清理”并重建项目,以得到正确的resurces编译,这是来自Eclipse的东西。onPostCreate()方法在内容完全加载时执行。接受答案,plz=)谢谢你的解释。只是学究一点,
onPostCreate
实际上是用于框架的,通常不用于应用程序中。任何逻辑都应该包含在
onCreate
的末尾。@manelizzard但我正在更改
onCreate()之后的内容视图。
!。使用
findViewById()
获取空值。请包含更多信息。您需要更清楚地解释您的答案。否则,即使它是正确的,也不会太有用。应用程序需要两个事件:onCreate()和onStart(),这两个事件是您将此函数放入其中的事件。
newDeck.setOnClickListener(this);
    @Override
protected void onStart() {
         // use findViewById() here instead of in onCreate()
    }