2020 Drive Code null pointerexception

When I tried writing joystick code for the new 2020 code format, I ran into a problem. I declared the joystick port in constants, declared the joystick in RobotContainer, and then declared the x, y, and twist axises and drivetrain subsystem function in the Drive command shown here:

I got the error shown in the comment below

Error:
unnamed-1

Has robotContainer.stick been initialized

Yes.
In my robotcontainer, I have joystick stick = new Joystick(port number)
In my Drive command, I have joystick stick = container.stick.
I get no errors from these lines of code.

Can you post all of your RobotContainer.java?

When exactly is the joystick being initialized?

Robot Container Code:
unnamed-2

Try moving it to the beginning.

1 Like

Move what to the beginning of what?

Sorry I’m used to the discord programming help channel. Basically what I think is happening is that stick isn’t initialized until after drivetrain and its default command drive have tried to access it. Initialize then stick before anything else.

Since you use stick in your drive command, you can’t instantiate the drive command before instantiating stick.

This kind of problem is exactly why we don’t recommend using global variables. Consider following the pattern used in the various command-based example projects, instead.

2 Likes

I can’t believe I didn’t think of that.
Thanks for the help, it works now!

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.