In JavaFX I am creating a sports tracking system.
My Object User has many Foods and many Exercises, these are stored as ArrayLists.
public class User {
private ArrayList<Food> listofFood = new ArrayList<Food>();
private ArrayList<Exercise> listofExercise = new ArrayList<Exercise>();
private String um;
public User(String u) {
this.um = u;
}
public void addNewFood(Food f) {
listofFood.add(f);
}
public void addNewExercise(Exercise ex) {
listofExercise.add(ex);
}
}
Food and exercise are similar in structure.
public class Food {
private String name;
public Food(String n) {
this.name = n;
}
public void setNameFood(String n) {
this.name = n;
}
}
In my MainApp class I create a user.
public class MainApp {
public User UserLoggedIn;
}
and I pass in an instance of this class using the controller.
public class MainApp {
MyController c = loader.getController();
c.setDialogStage(dialogStage);
c.setApp(this);
}
And in MyController class I set the application ...
public class MyController {
public void setApp(MainApp app) {
this.mainApp = app;
}
}
... which I then reference in MyController.
public class MyController {
mainApp.UserLoggedIn.addNewFood((new Food(nameField.getText())));
}
This gives a Null Pointer exception
UserLoggedIn is never instantiated and it will therefore always be null. Make a default constructor for MainApp() that just creates the User object. Then create a getter method called getUser() that returns the user object. Also, it is Java convention to use camel case instead. So, UserLoggedIn should be userLoggedIn.
public class MainApp
{
private User userLoggedIn;
public MainApp()
{
userLoggedIn = new User("john doe");
}
public User getUserLoggedIn()
{
return userLoggedIn;
}
}
public class MyController
{
MainApp mainApp = new MainApp();
mainApp.getUserLoggedIn().addNewFood(new Food(//enter datum here));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.