I'm new to both Java and Android Studio (1 day's experience in each).
I'm making a test app where you tap a walnut and a counter goes up by one each time, pretty simple. The app was running perfectly fine, however, this morning it stopped running properly, and the app stops whenever I try to run it.
I've tried a couple things and have narrowed it down to a line and an error, but I'm not sure what to make of it.
I understand what a NullPointerException is, but I have no idea how to fix it in this case. Since I'm new to the IDE and language, any suggestions about anything in the code is absolutely welcome too!
The app is made up of 2 classes as of now:
MainActivity.java :
package com.nut.calendar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
//WIDGETS
ImageButton nutButton = findViewById(R.id.nutButton);
TextView nutNum = findViewById(R.id.nutsNum);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Variables.nutCount += 1;
nutNum.setText(String.valueOf(Variables.nutCount));
}
});
}
}
Variables.java :
package com.nut.calendar;
public class Variables{
public static int nutCount = 0;
}
The error points to line 12 in 'MainActivity.java' :
ImageButton nutButton = findViewById(R.id.nutButton);
And the error in Logcat says :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
I would really appreciate any input!
Here's the whole Stack Trace: Error