Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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!

like image 423
Neuhier Avatar asked Aug 21 '11 10:08

Neuhier


1 Answers

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

like image 51
manelizzard Avatar answered Oct 27 '22 16:10

manelizzard