-1

I know this has been asked numerous times but since I'am a beginner I couldn't understand any of the solutions. I wrote a simple app to count up and down from 0 but the app kept crashing. After reading through StackOverFlow I learnt about Stack trace and found what the problem was but was not able to fix. Here is my code

MainActivity.java:

package com.example.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    int counter;

    {
        counter = 0;
    }

    Button add,sub;
TextView display;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                counter++;
                display.setText("Count: " +counter);

            }
        });
        sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                counter--;
                display.setText("Count: " +counter);

            }
        });
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="107dp"
        android:layout_marginBottom="8dp"
        android:text="@string/Title"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.133" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="217dp"
        android:text="@string/add"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.754" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="@string/sub"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.511"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        app:layout_constraintVertical_bias="0.005" />

</android.support.constraint.ConstraintLayout>

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Logcat:

2019-02-17 20:36:55.107 3748-3748/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 3748
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: 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:2926)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3061)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
        at android.os.Handler.dispatchMessage(Handler.java:114)
        at android.os.Looper.loop(Looper.java:198)
        at android.app.ActivityThread.main(ActivityThread.java:6716)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     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.example.myapplication.MainActivity.onCreate(MainActivity.java:22)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2906)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3061) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 
        at android.os.Handler.dispatchMessage(Handler.java:114) 
        at android.os.Looper.loop(Looper.java:198) 
        at android.app.ActivityThread.main(ActivityThread.java:6716) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
  • You declare some variable (`add`, `sub`, `display`) but never assign any value to it and then try to use it, of course, null pointer exception throws. I think you should understand some fundamentals of programming, such as variable, variable assignment, pointer/reference...etc. before you code complex things. – Rex Lam Feb 17 '19 at 15:58
  • How do I fix it then? Should I set them to Null at the beginning? – Reppin Frost Feb 17 '19 at 16:39
  • 1
    Duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Phantômaxx Feb 17 '19 at 16:43
  • What changes to the program do I need to do? – Reppin Frost Feb 17 '19 at 16:59
  • You need to instance the object which is null **before** it's used. – Phantômaxx Feb 17 '19 at 17:57

1 Answers1

0

You have declared the button variables (add and sub) and the textview variable (display), but you never assigned the respective Button and TextView objects to them.

You have to create two buttons objects:

add = (Button)findViewById(R.id.button);
sub = (Button)findViewById(R.id.button2);

And also a TextView object:

display = (TextView)findViewById(R.id.textView);

After the assignment you proceed with adding the listeners to the button objects.

weaklin
  • 56
  • 6
  • I did have this in my code but I got an redundancy warning with it. – Reppin Frost Feb 18 '19 at 00:16
  • But thank you, this helped. – Reppin Frost Feb 18 '19 at 00:17
  • Why would you get a redundancy warning? Do you init and assign values to the Button and TextView objects anywhere else in your code (explicitly in your activity)? Ever way glad to help. – weaklin Feb 18 '19 at 13:18
  • `Button add = (Button)findViewById(R.id.button); Button sub = (Button)findViewById(R.id.button2); TextView display = (TextView)findViewById(R.id.textView);` I added this at the declaration but I'm still getting a NullPointerException. – Reppin Frost Feb 18 '19 at 13:24
  • Comparing the code you posted and the comment I can asume you declare the Button and TextView before your onCreate method.So when you init those object inside the onCreate you don't have to declare them again. Simply set add = (Button)findViewById(R.id.button); sub = (Button)findViewById(R.id.button2); display = (TextView)findViewById(R.id.textView); – weaklin Feb 18 '19 at 13:28
  • It worked, thank you. – Reppin Frost Feb 18 '19 at 14:18