findViewById returns NULL


#1

findViewById is returnning NULL which crashes the app. I spent lots of time searching for answer but no luck. Can someone please help?

[code]public class QuizActivity extends ActionBarActivity {

private Button mTrueButton;
private Button mFalseButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
    
    mTrueButton = (Button)findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
    	@Override
    	public void onClick(View v) {
    		Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT).show();
    		
    	}
    });
    mFalseButton = (Button)findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
    	@Override
    	public void onClick(View v) {
    		Toast.makeText(QuizActivity.this, R.string.incorrect_toast, Toast.LENGTH_SHORT).show();
    	}
    });
}[/code]

#2

You should have a line similar to this in R.java under the gen folder:

You should have a similar line for true_button.

If those aren’t there, check your activity_quiz.xml file for typos in this line and the similar one for true_button:


#3

Thanks for the reply. Yes, I did make sure there are no typos and all the resources are set up correctly.

I ended up doing the same solution as someone mentioned in another topic where mTrueButton is nil. But I don’t understand why we have to do it that way in PlaceholderFragment inner class. I suppose this book is not up to date with the new API standards.


#4

I have the same problem here with the latest ADT. It seems that it has something to do with the fragment layout sitting in the middle of the main container and the actual controls.

[quote=“shogen”]Thanks for the reply. Yes, I did make sure there are no typos and all the resources are set up correctly.

I ended up doing the same solution as someone mentioned in another topic where mTrueButton is nil. But I don’t understand why we have to do it that way in PlaceholderFragment inner class. I suppose this book is not up to date with the new API standards.[/quote]


#5

If you want to follow the the book, you’ll want to get rid of that fragment completely and just start with an activity. http://stackoverflow.com/questions/22289164/adt-blank-activity-created-with-fragment-activity