Neuhier
Neuhier

Reputation: 83

NullPointerException in onCreate() when using findViewById - setContentView is used before?

Hello I'm writing a little Android app (Version 2.3.3). Now i get this strange NullPointer Exception in this very basic code:

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);
}

Im using this simple layout at the moment in 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>

Now my problem is a nullpointexception in line 25, which is the line where i set the first clickListener

newDeck.setOnClickListener(this);

Using the debugger i figured out that the button newDeck is null. I searched a lot in the web but the only answer to such kind of problem was to check that the setContentView is set before the findViewById. This is obviously the case here.

I would be very glad for any kind of advice.

Thx in Before!

Upvotes: 8

Views: 4357

Answers (2)

Jonathan
Jonathan

Reputation: 7118

There are two events that the App expects, onCreate(), and onStart()

Which one you put this function in, matters.

I had to move "findViewByID" from onCreate() to onStart()

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

Upvotes: -2

manelizzard
manelizzard

Reputation: 1058

Get your views and set the listeners in onPostCreate() method.

Upvotes: 10

Related Questions