Serial Event null pointer exception

Before anything else, you should get rid of all those moot try/catch () blocks.

Its need is rare in Processing, b/c most exceptions are simply swallowed up by the API.

So your serialEvent() callback should be as plain simple as this:

void serialEvent(final Serial s) {
  val = s.readString().trim();
  redraw();
}

Now, back to r(coordinates.size() - 1);, I wonder where you initialize the List coordinates variable?

I could only spot this statement and no new for it: List<deltaXY> coordinates;

You should replace that w/: final List<deltaXY> coordinates = new ArrayList<deltaXY>();.

Also, you should consider initializing your String val variable w/ something which could be parsable as a JSONObject.

For example, something like this: String val = "{}";.

It’s important to do so b/c very likely draw() is gonna be called back much before serialEvent() would have a chance to initialize val w/ the received data.

Well, I’ve adapted my old sketch “Efficient Serial Reading” to get a JSON data and store it in a Point2D.Float container as a simplified example:
Docs.Oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/geom/Point2D.Float.html

Given I don’t have the hardware to test it myself, it’s up to you to check it out whether it works or not: :flushed:

// Discourse.Processing.org/t/serial-event-null-pointer-exception/13275/4
// GoToLoop (2019/Aug/09)

import processing.serial.Serial;
import java.awt.geom.Point2D;

static final int PORT_INDEX = 0, BAUDS = 115200;
final Point2D.Float xy = new Point2D.Float();
String myString = "{}"; // represents an empty json object

void setup() {
  size(400, 400);
  noLoop();

  stroke(#FFFF00);
  strokeWeight(1.5);

  final String[] ports = Serial.list();
  printArray(ports);
  new Serial(this, ports[PORT_INDEX], BAUDS).bufferUntil(ENTER);
}

void draw() {
  println(frameCount + ": " + myString);
  final JSONObject json = parseJSONObject(myString);
  println(json);

  if (json == null || json.size() < 2)  return;
  final float x = json.getFloat("lat"), y = json.getFloat("lng");

  clear();
  if (frameCount > 2)  line(xy.x, xy.y, x, y);
  else                 point(x, y);

  xy.setLocation(x, y);
  println(xy);
}

void serialEvent(final Serial s) {
  myString = s.readString().trim();
  redraw = true;
}
1 Like