I am new to android and i am trying to make a stopwatch but dont know whats wrong with my code. I am getting this error-
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Please help.
StudyTimeFragment.java
package com.studypal.khadija.studypal;
import android.app.Fragment;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Chronometer;
public class StudyTimeFragment extends Fragment {
public Button startbutton;
public Chronometer studywatch;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_studytime, container, false);
startbutton=(Button)rootView.findViewById(R.id.button);
studywatch = (Chronometer)rootView.findViewById(R.id.chronometer);
startbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
studywatch.setBase(SystemClock.elapsedRealtime());
studywatch.start();
return;
}
});
return rootView;
}
}
fragment_studytime.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Chronometer
android:layout_width="88dp"
android:layout_height="91dp"
android:id="@+id/chronometer"
android:layout_gravity="top|center"
android:layout_marginTop="175dp"
android:width="150dp"
android:height="150dp"
android:textSize="70dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_gravity="top|center"
android:text="Start"
android:clickable="true"
android:onClick=""
/>
</FrameLayout>
It looks like your button needs an ID, the same one that you are looking for in your fragment onCreateView.
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_gravity="top|center"
android:text="Start"
android:clickable="true"
android:onClick=""
/>
Note the new android:id property.