Arduino and Processing gives NullPointerException

Hello @Ties2901,

For the NullPointerException:

https://forum.processing.org/two/discussion/8071/why-do-i-get-a-nullpointerexception

if data[] has not yet been initialized it is a null.
You are trying to read this in draw() and it gives a NullPointerException if there is no data received yet in data[].

Try this in draw():

  if(data != null)
  {
  // Your code...
  }

Take a look at how the code checks for null in the serialEvent().

There are also other ways to check and flag valid data… welcome to serial programming!

Which version of Processing are you using?

If I get a sketch that is locked up I will sometimes wait it out…

The other option is to use Windows Task Manager and for “OpenJDK Platform binary” you will “End task”:

image

Make sure you routinely save files so you do not lose your work.

This is good to add to setup() to check available serial ports:
https://processing.org/reference/libraries/serial/Serial_list_.html

This is a common error if you select a serial port this is not available:

Update:

This is what your code is doing if inString is null and generates a NullPointerException:

String [] data;

void setup()
  {
  //String inString = "0.1,2.1,3.3" + "\r\n";
  String inString = null;
  if (inString != null)
    inString = trim(inString);
    
  // It may still be null here... 
  data = split(inString, ",");
  
  printArray(data); 
  }

This will catch the null:

String [] data;

void setup()
  {
  //String inString = "0.1,2.1,3.3" + "\r\n"; // Try with this... 
  String inString = null;  // Or with this 
  if (inString != null)
    {  
    inString = trim(inString);
    data = split(inString, ",");
    printArray(data); 
    }
  }

You may also want to add a check to see of the array size is correct after receiving data.

:)

2 Likes