enzom83
enzom83

Reputation: 8310

NullPointerException in onCreate() method while handling an event

I created a new Android project (for android 2.3.3) using Eclipse and I modified the main.xml file in res/layout folder as follows.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center" >

    <Button android:id="@+id/button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button01_name" />

</LinearLayout>

The strings.xml file in res/values folder is as follows.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ButtonClickDemo3</string>
    <string name="button01_name">Press this button!</string>

</resources>

Finally, here is the onCreate() method of the one Activity of the project.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Button button01 = (Button) findViewById(R.id.button01);
    button01.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast toast = Toast.makeText(v.getContext(), "The button was pressed!", Toast.LENGTH_SHORT);
            toast.show();
        }
    });

    setContentView(R.layout.main);

}

When I run this simple application, a NullPointerException is thrown on button01.setOnClickListener(...). Indeed, if I move the setContentView(R.layout.main); instruction writing it before creating the button, that is

...

setContentView(R.layout.main);

Button button01 = (Button) findViewById(R.id.button01);
button01.setOnClickListener(...);

...

the application works successfully. Why?

Upvotes: 0

Views: 217

Answers (3)

Jon Wells
Jon Wells

Reputation: 4259

You have to set the contentView first otherwise how do you expect findViewById to find the views. This is why your getting a null pointer. button01 is a View on R.layout.main therefore you must set your contentView first

Upvotes: 3

luciferche
luciferche

Reputation: 134

It is because your activity in the time of defining button doesn't know in which layout should it search for id/button01

Upvotes: 1

Shashank Kadne
Shashank Kadne

Reputation: 8101

setContentView(R.Layout.main) is missing in your onCreate() method

Upvotes: 0

Related Questions