javaandroidandroid-studiogpslocation

NullPointerException when calling setOnClickListener for a button - Android Studio


I've started to learn Java and Android Development and as a first excercise I am trying to develop a Speedometer app for Android which uses a custom Location Service, the problem seems to be that when I initialize the buttons in the OnCreate Method these cannot be found.

The app is based on the scroll template.

This is the OnCreate Method:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_speedometer);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();


    speedText = (TextView) findViewById(R.id.speedText);
    unitText = (TextView) findViewById(R.id.unitText);
    startButton = (Button) findViewById(R.id.startButton);
    resetButton = (Button) findViewById(R.id.resetButton);
    

    if (!runtimePermissions()) //Will call a method that checks Location services are permitted.
    {
        enableButtons();
    }
}

This is the eneableButtons() method that seems to cause the problem

 private void enableButtons() //using this method will not require the use of two buttons for On/Off
    {
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startClickCount++; //Counts how many time the button has been clicked
                if (startClickCount % 2 == 0) //If it is even
                {
                    Intent i = new Intent(getApplicationContext(), GPSService.class);
                    startService(i);

                }
                else
                {
                    Intent i = new Intent(getApplicationContext(), GPSService.class);
                    stopService(i);
                }

            }
        });
    }

This is my fragment_speedometer.xml EDIT

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.amp.systems.performancespeedometer.Speedometer$PlaceholderFragment">


<Button
    android:text="Reset Info"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="181dp"
    android:id="@+id/resetButton" />



<TextView
    android:text="999"
    android:textSize="100dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/speedText"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="100dp" />

<TextView
    android:text="Km/h"
    android:textSize="25dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/unitText"
    android:layout_below="@+id/speedText"
    android:layout_centerHorizontal="true" />

<Button
    android:text="Start"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:layout_marginStart="24dp"
    android:layout_marginBottom="65dp"
    android:id="@+id/startButton" />

And this is the Log I get when deploying:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.amp.systems.performancespeedometer, PID: 4090
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amp.systems.performancespeedometer/com.amp.systems.performancespeedometer.Speedometer}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                  at com.amp.systems.performancespeedometer.Speedometer.enableButtons(Speedometer.java:160)
                  at com.amp.systems.performancespeedometer.Speedometer.onCreate(Speedometer.java:154)
                  at android.app.Activity.performCreate(Activity.java:6679)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                  at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6119) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 


<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.amp.systems.performancespeedometer.Speedometer">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

The app just crashes when executed.

Thanks in advance!


Solution

  • Looks like that startButton is null because it is not present in activity_speedometer.xml