Arduino and Processing gives NullPointerException

Hi glv,

Thanks for your reply and explanation.
I understand that if data is not initialized it is null so I have to clarify what processing needs to do if data is not null, but receiving. Placing this in my code has helped with the nullpointerexception so that is good! I can run the sketch now, but nothing is happening.
When I place the background outside of the IF statement I get the nullpointer exception again… That is strange because I also want to display the background when I am not recieving any data and so when data is null. I am confused because when I look in the Arduino IDE that I am using, the serial monitor is clearly receiving data of the joystick when I move it.

I have also checked which Serial Port i was supposed to be using! Thanks for the tip, I was in the wrong port.

Regarding checking for null in the serialEvent() function i have used the general code that my University has given.

I also have now the problem that when I am typing in Processing, my text ‘overlaps’ and writes over + deletes the text that is allready there… any shortcuts to stop this from happening?

Thanks

/*
DATE: 23_10_2022
 CREATIVE CHALLENGE 2: EGBERT THE FISH GAME_version_3
 AUTHOR: TAISSIA VISSER
 REFERENCES:
 https://www.youtube.com/watch?v=jUmjbFsA2zw&ab_channel=Crazy-Logic
 */

// Importing the serial library.
import processing.serial.*;

// Declare serial communication port
Serial myPort;
String inString;
String[] data;    // Array of data received from the serial port

// Declare game characters
PImage Campus;
PImage Egbert;
PImage Bottle;
PImage Corn;
PImage Bread;

void setup() {
  size (1920, 1081);
  String myPortName = Serial.list()[2];
  myPort = new Serial(this, myPortName, 9600);
  myPort.bufferUntil('\n');
  //intArray(Serial.list());

  //Campus = loadImage("Egbertbackground.jpg");
  //Egbert = loadImage("Egbert.png");
  //Bottle = loadImage("plastic.png");
  //Corn = loadImage("corn (1).png");
  //Bread = loadImage("bread.png");
}

void draw() {
  background(Campus);
  if (data != null)
  {
    int xPos = int(data[0])/2;
    int yPos = int(data[1])/2;
    int Pressed = int(data[2]);
    image(Egbert, xPos, yPos);
  }
  //image(Bottle, 100, 100);
  //image(Corn, 300, 300);
  //image(Bread, 400, 200);
}

// will get called every time data comes in
// storing the data string here
void serialEvent(Serial myPort) {
  String inString = myPort.readStringUntil('\n');
  if (inString != null)
    // removing the whitespace
    inString = trim(inString);
  // Splitting the string at the commas and
  // seperating the variables out into an array
  data = split(inString, ",");
}