Reputation: 27
My problem is exactly as the title states.
I have a Tracker.class, a TrackerGUI.class and a TrackerApp.class (driver for JFrame). Tracker class is initialised in the TrackerGUI.class as private Tracker tracker
The code itself compiles properly (so I'm guessing that means there are no syntax errors, but when I try to add an object, Terminal pops up (I'm using BlueJ), and gives me this error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at TrackerGUI$Food.actionPerformed(TrackerGUI.java:121)
clicking that would lead me to:
public class TrackerGUI extends JFrame {
private Tracker tracker;
double calories;
double quantity;
// more initialising of GUI elements; so all the JTextField things are initialised
// setting up the GUI code, too
public class Food implements ActionListener {
public void actionPerformed (ActionEvent ae) {
double calories = Double.parseDouble(caloriesField.getText().replaceAll(",",""));
String newFood = activityField.getText();
if(calories < 0) {
textArea.append("Calories cannot be negative. \n\n");
}
else {
tracker.addFood(newFood, calories); // this line!
textArea.append(newFood + " with " + calories + " calories added to database! \n");
}
}
}
In the tracker class, the code for addFood is such:
public class Tracker {
ArrayList<Food> foodBase = new ArrayList<Food>();
String foodName;
Double calories;
public void addFood(String foodName, double calories)
{
Food newFood = new Food(foodName, calories);
foodBase.add(newFood);
}
What is missing in my code? Note: I have to use ArrayList
and I can't use List
or Map
I feel like I'm missing a for
statement that gets foodBase.size()
but I'm not sure where it would fit?
Upvotes: 0
Views: 107
Reputation: 11321
change this:
else {
tracker.addFood(newFood, calories); // this line!
textArea.append(newFood + " with " + calories + " calories added to database! \n");
}
to:
else if (tracker != null){
tracker.addFood(newFood, calories); // this line!
textArea.append(newFood + " with " + calories + " calories added to database! \n");
}
to ensure you don't execute this code if tracker is null AND make sure before that you initialized the tracker properly before:
private Tracker tracker = new Tracker(); // initialize your tracker!!
Upvotes: 0
Reputation: 692231
ArrayList<Food> foodBase = new ArrayList<Food>();
You're declaring and initializing a local variable in your constructor, which happens to have the same name as the field, used in the addFood()
method. It should be
this.foodBase = new ArrayList<Food>();
EDIT: reading the exceptin again, it seems you also forgot to initialize the tracker
in the class containing the Food
inner class (TrackerGUI
)
Upvotes: 1