Triggering a command with a button gives us a null pointer exception (java)

Triggering a command gives us a null pointer exception.

The error:

Unhandled exception: java.lang.NullPointerException
Error at java.base/java.util.Objects.requireNonNull(Unknown Source): Unhandled exception: java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Unknown Source)
The robot program quit unexpectedly. This is usually due to a code error.
The above stacktrace can help determine where the error occurred.

at java.base/java.util.ImmutableCollections$Set12.(Unknown Source)
The startCompetition() method (or methods called by it) should have handled the exception above.
at java.base/java.util.Set.of(Unknown Source)
at edu.wpi.first.wpilibj2.command.CommandBase.addRequirements(CommandBase.java:32)
at frc.robot.commands.turn.(turn.java:40)
at frc.robot.RobotContainer.configureButtonBindings(RobotContainer.java:442)
at frc.robot.RobotContainer.(RobotContainer.java:67)
at frc.robot.Robot.robotInit(Robot.java:53)
at edu.wpi.first.wpilibj.TimedRobot.startCompetition(TimedRobot.java:107)
at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:373)
at edu.wpi.first.wpilibj.RobotBase.startRobot(RobotBase.java:463)
at frc.robot.Main.main(Main.java:23)
Warning at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:388): The robot program quit unexpectedly. This is usually due to a code error.
The above stacktrace can help determine where the error occurred.

Error at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:395): The startCompetition() method (or methods called by it) should have handled the exception above

This is our code for triggering the command:

Preformatted text private void configureButtonBindings() {

Joystick joystick = new Joystick(1);

JoystickButton RB = new JoystickButton(joystick, 6);

RB.whenPressed(



new turn(driveTrain, gyro, elevator, 180)

 

);



/* RB.whenPressed(

  new turn(driveTrain, gyro, intake, elevator, 180)

); */

}
’

Through some testing we have figured out that the reason for the null pointer has something to do with the instantiation of our subsystems and how we are passing it into the command.

Here is our github link if you want a more detailed version of the code:

Github link

Thanks in advance.

In RobotContainer.java, you’re calling configureButtonBindings in line 67 prior to instantiating your subsystem objects. The issue is that the button bindings function uses the subsystems for the turn command. Since those objects haven’t been instantiated yet, they are null and the turn command is being given a null object.

I haven’t looked much deeper into the rest of your code but to fix the null pointer you should just move the configureButtonBindings function call to after the initialization of your subsystems, around line 78.

Hope that helps

2 Likes

Thank you for catching that! we will test that tomorrow.

1 Like