Link to home
Start Free TrialLog in
Avatar of Karl01
Karl01

asked on

Why does the Android Studio logcat show this error when the user presses the button?

Hi, whilst attempting to add functionality to a button in Android Studio, the following error is shown in the logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I am trying to get the button to direct the user to another activity when clicked. This is the java code that I have produced in order to add this function to the button:
Button physics_button = (Button) findViewById(R.id.physbutton);
physics_button.setOnClickListener(new View.OnClickListener(){
    public void onClick(View view){
        Intent intent = new Intent (MainActivity.this, RevisePhysics.class);
        startActivity(intent);
    }
});

Open in new window

The button ID has been made the same as the ID within the ‘MainActivity’ XML file:
<Button
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Physics"
    android:id="@+id/physbutton"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:textSize="50dp"
    android:background="#82020202"
    android:textColor="#ffffff"
    android:fontFamily="Open Sans"
    android:onClick="onClick"/>

Open in new window

The activity ‘RevisePhysics’ has been created:
 User generated imageSo I don’t understand why the error shown is stating the app is attempting to call a null object reference.
This button previously worked until I added content to the activity ‘RevisePhysics’ which, to my knowledge, shouldn’t affect the functionality of the button on ‘Main Activity’.
Thank you in advance for any replies.
ASKER CERTIFIED SOLUTION
Avatar of Chris Harte
Chris Harte
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial