danbli1 danbli1 - 5 months ago 9
Java Question

Android add button crash the app

I am trying to add a simple button to my application but I got the next error and I do not know what to do, I would be happy if any one can help me understand the problem and fix that.

Error message -


Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference


Code -

final Button settings = (Button) findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), Settings.class);
startActivity(i);
}
});


xml -

<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:id="@+id/settings"
android:src="@drawable/settings"
android:background="@drawable/settings"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="70dp"
android:layout_marginRight="10dp" />


P.S(This is the second button I try to add the first one work fine).

Thanks.

Answer

This seems to be reference problem. Maybe more than one button with same id are present.

However to make this easier you can also set onClick attribute in your button view.

For example:

<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:id="@+id/settings"
android:src="@drawable/settings"
android:background="@drawable/settings"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="70dp"
android:layout_marginRight="10dp"
android:onClick="ButtonClick" />

and in your java class

public void ButtonClick(View v){
Intent i = new Intent(getBaseContext(), Settings.class);
        startActivity(i);
}
Comments