Narabhut
Narabhut

Reputation: 837

Onclick listener throwing NullPointerException

I've setup a button and I'm trying to display a toast when the user clicks on it. Here's my Java code -

file = (Button) findViewById(R.id.file);

file.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Display the file chooser dialog
                //showChooser();
                Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
            }
        });

Here's my XML code to setup the button -

<Button
            android:id="@+id/file"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/plt"
            android:text="File" />

This throws a NullPointerException on the line file.setOnClickListener(new OnClickListener() { . What am I doing wrong?

Upvotes: 1

Views: 630

Answers (3)

Philipp Jahoda
Philipp Jahoda

Reputation: 51411

Are you initializing the Button inside the onCreate() method of your Activity?

If so, please check if you are calling

setContentView(R.id.yourlayoutfile);

before initializing the Button with findViewById(R.id.file);

Your error occurs because your Button "file" is null, which means that findViewById(...) didn't find any View with that id. The reason therefore can either be that there is no such ID in the inflated layout, or that you didn't call setContentView(...)

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourlayoutfile);

        // initialize your button here  
    }

Upvotes: 3

Bishoy Fakhry
Bishoy Fakhry

Reputation: 161

try to clean project

project-->clean-->choose your project-->ok, then run again.

if you still facing the same problem you can use another way to set click action

in your XML

<Button
        android:id="@+id/file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/plt"

        <!--added line-->            
        android:onClick="anyName"

        android:text="File" />

and then in you activity remove the initialization of the button and click listner too

and make the code looks like that

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.id.yourlayoutfile);
}

public void anyName(View v){
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
   Toast.LENGTH_LONG).show();

}

Hope this help.

Upvotes: 1

Juned Ahsan
Juned Ahsan

Reputation: 68715

If there is a Null pointer exception on this line:

file.setOnClickListener(new OnClickListener() 

then it mean your file object is null

Make sure you initialize your file object before adding a listener to it.

Upvotes: 0

Related Questions