Seth Nelson
Seth Nelson

Reputation: 2608

Button not fetched from XML? Null Pointer

newSubmitButton = (Button) findViewById(R.id.newPlayerSubmit);
Log.v("heeelp",""+newSubmitButton);

Seems simple enough. I have a global Button variable called newSubmitButton. I fetch the Button from an xml file in the project (I promise, the button exists, i didn't mispell the name, etc.) I output the button in the next line, it is null. I try to give it an onClickListener and it throws a null pointer exception. How is this button null? I just instantiated it the line before!

Upvotes: 1

Views: 276

Answers (3)

Mark B
Mark B

Reputation: 200672

I just instantiated it the line before!

No you didn't,

newSubmitButton = (Button) findViewById(R.id.newPlayerSubmit)

does not instantiate anything. It simply retrieves the button from the active view. If the button isn't part of the active view (perhaps the layout hasn't been inflated yet?) then your button reference will be null. Are you calling this code in your Activity's onCreate() method? Have you called setContentView() before executing the code in question?

Upvotes: 1

num1
num1

Reputation: 4975

Did you remember to setContentView() higher up? Just because R.java contains it doesn't mean it's attached to your view.

Upvotes: 1

Computerish
Computerish

Reputation: 9591

Besides misspelling the name, you might have left out a call to setContentView().

(If that's not the issue, please post more code.)

Upvotes: 1

Related Questions