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

Hello, I am writing a small Android application (version 2.3.3). Now I get this weird NullPointer exception in this very base 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 currently in the main .xml menu:

 <?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 the nullpoint error on line 25, which is the line where I set the first clickListener

 newDeck.setOnClickListener(this); 

Using the debugger, I realized that the newDeck button is null. I searched a lot on the net, but the only answer to this problem was to verify that setContentView was set before findViewById. This is obviously here.

I would be very happy for any advice.

Thanks in Before!

+8
android
source share
2 answers

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

+10
source share

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

Which one you entered this function matters.

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

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

All Articles