# Can't figure out how to fix this NullPointerException

**URL:** <https://discourse.processing.org/t/cant-figure-out-how-to-fix-this-nullpointerexception/11441>\
**Category:** Electronics (Arduino, etc.)\
**Created:** [May 20, 2019, 8:44pm UTC](https://discourse.processing.org/t/cant-figure-out-how-to-fix-this-nullpointerexception/11441 "2019-05-20T20:44:07Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![kiraraew](https://avatars.discourse-cdn.com/v4/letter/k/f14d63/32.png) [@kiraraew](https://discourse.processing.org/u/kiraraew)\
**Post date:** [May 20, 2019, 8:44pm UTC](https://discourse.processing.org/t/cant-figure-out-how-to-fix-this-nullpointerexception/11441/1 "2019-05-20T20:44:07Z")

</div>

I am new to Processing, only have been working with it for a few months now, and I’m trying to create a program that takes data from Arduino and uses that to send out a tweet using Twitter4j.

I’ve narrowed down the code to where I think the problem areas might be, but I keep on getting the NullPointerException error where it says “sensorInt = int(sensorValue);”. I was wondering if anyone could help me out on this one. Thanks! 🙂

````auto

Arduino arduino;
Twitter twitter;
Serial myPort;
String sensorValue;
int sensorInt;

void setup()
{  
  String portName = Serial.list()[5]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
  sensorInt = 246;

  TwitterFactory tf = new TwitterFactory(cb.build());

  twitter = tf.getInstance();
}  
void draw()
{
  sensorValue = trim(myPort.readStringUntil('\n'));
  sensorInt = int(sensorValue);
  println(sensorValue);
  if (sensorInt < 230)
  {
    tweet();
  }
  delay(500);
}```
````

---

<div class="post-metadata">

**Author:** ![TfGuy44](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/tfguy44/32/41_2.png) [@TfGuy44](https://discourse.processing.org/u/TfGuy44)\
**Post date:** [May 20, 2019, 10:05pm UTC](https://discourse.processing.org/t/cant-figure-out-how-to-fix-this-nullpointerexception/11441/2 "2019-05-20T22:05:42Z")

</div>

Two things jump out at me as being wrong immediately.

First, you’re getting a String for `sensorValue`, and then assuming that what you got was a String that looks like an int. This might not be the case. You should check for this situation to avoid the NPE you are getting:

```auto
  sensorValue = trim(myPort.readStringUntil('\n'));
  if( sensorValue ) { // is not a null value
    sensorInt = int(sensorValue);
    // ..whatever else you do when you get a new value.
  }

```

The second mistake is the call to `delay(500)`. You do not want this in your code AT ALL - especially not in your main draw loop!

… I feel like I haven’t stressed how wrong this is. Here is some insane gibberish ranting to drive the point home:

NO NO NO A MILLION TIMES NO DELAY IS NOT WHAT YOU WANT NO NO REMOVE IT NOT DELAY NO PLEASE LORD NOT DELAY DONT USE DELAY THAT IS NOT THE FUNCTION YOU WANT TO CAUSE A DELAY DONT USE DELAY NOT DELAY THAT IS WRONG AND BAD AND NO DONT USE DELAY

_ahem_

Instead, consider using millis():

```auto
int time;

// In setup(), time = millis();

void draw(){
  if( time + 500 > millis() ){
    time = millis();
    // Any other actions you want to happen ever half a second,
    // Perhaps things like reading a new value from your port.
  } // End if
} // End draw

```

---

<div class="post-metadata">

**Author:** ![kiraraew](https://avatars.discourse-cdn.com/v4/letter/k/f14d63/32.png) [@kiraraew](https://discourse.processing.org/u/kiraraew)\
**Post date:** [May 21, 2019, 2:58am UTC](https://discourse.processing.org/t/cant-figure-out-how-to-fix-this-nullpointerexception/11441/3 "2019-05-21T02:58:15Z")

</div>

Hi! Thank you so much for the reply, it means a ton! I am a little bit confused on what you put in the parenthesis on this line:

> [@TfGuy44](#):
>
> if( sensorValue ) { // is not a null value

It’s just giving me “Type mismatch, “java.lang.String” does not match with “boolean”” because the variable sensorValue is a string. I was also confused by the statement you said at the very beginning.

> [@TfGuy44](#):
>
> First, you’re getting a String for `sensorValue` , and then assuming that what you got was a String that looks like an int. This might not be the case. You should check for this situation to avoid the NPE you are getting

The sensorValue variable is the constant string of numbers I’m receiving from my Arduino device and I want to change that string into an int so that way I can use it to see if that value is less than 230.

---

<div class="post-metadata">

**Author:** ![kiraraew](https://avatars.discourse-cdn.com/v4/letter/k/f14d63/32.png) [@kiraraew](https://discourse.processing.org/u/kiraraew)\
**Post date:** [May 21, 2019, 3:06am UTC](https://discourse.processing.org/t/cant-figure-out-how-to-fix-this-nullpointerexception/11441/4 "2019-05-21T03:06:34Z")

</div>

Oh wait, haha I’m just tired. I figured out what you meant.

```auto
void draw() {
  if ( time + 500 > millis() ) {
    time = millis();

    if (sensorValue != null && !sensorValue.isEmpty()) {
      sensorInt = int(sensorValue);
      println(sensorValue);
      tweet();
    }
  }
}

```

Looking better? I don’t get the null error anymore! 👍 😄

---

<div class="post-metadata">

**Author:** ![raron](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/raron/32/13651_2.png) [@raron](https://discourse.processing.org/u/raron)\
**Post date:** [May 21, 2019, 3:10am UTC](https://discourse.processing.org/t/cant-figure-out-how-to-fix-this-nullpointerexception/11441/5 "2019-05-21T03:10:44Z")

</div>

Just a comment on the delay() thing.

> [@TfGuy44](#):
>
> The second mistake is the call to `delay(500)` . You do not want this in your code AT ALL - especially not in your main draw loop!

Agreed! And I’d like to add that making a home-brewed waiting loop “instead of delay()” is also a big NOPE! Something like `for(int i=0; i<9000000; i++) {}`, or similar.

> [@TfGuy44](#):
>
> Instead, consider using millis():

This. Btw, turn the condition around: `if( millis() > time + 500 ){`

But this way still have problems just before millis() rollover. Ok so it won’t happen for about 24 days and 8.5 hours (minus the interval time). So may (probably) not be needed. But if it is, then it will fire the condition constantly during the last interval period (just before millis() rollover).

Instead of comparing time points, compare time durations to avoid this:

`if( (millis() - time) > interval ) {`

Also works for unsigned integers (like the millis() function in Arduino, nicely explained [here](https://www.baldengineer.com/arduino-millis-plus-addition-does-not-add-up.html))

Test:

```auto
/** millis rollover test
*/

int lastTime;
int currentTime;
int rolloverSoonTest = 2147483647 - 4000;

final int interval = 1000;
boolean onState = false;

void setup() {
  size(400,400);
  
  lastTime = millis() + rolloverSoonTest;
}

void draw(){
  background(128);
  stroke(255);
  fill(255);
  currentTime = millis() + rolloverSoonTest;
  
  text("millis: " + currentTime, 50, 50);
  
  //if( currentTime > (lastTime + interval) ) { // using time points
  if( (currentTime - lastTime) > interval ) { // using time durations
    lastTime = currentTime;
    onState = !onState;
  }

  if (onState) fill(255,0,0); else fill(0);
  circle(200,200,50);

}

```

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [May 21, 2019, 3:19am UTC](https://discourse.processing.org/t/cant-figure-out-how-to-fix-this-nullpointerexception/11441/6 "2019-05-21T03:19:16Z")

</div>

Processing’s already got **frameRate()** to control its **draw()** looping’s FPS: 🤓  
[Processing.org/reference/frameRate\_.html](http://Processing.org/reference/frameRate_.html)

Use **delay()** to temporarily pause other threads, not the main “Animation Thread”. 🧐

---

<div class="post-metadata">

**Author:** ![kiraraew](https://avatars.discourse-cdn.com/v4/letter/k/f14d63/32.png) [@kiraraew](https://discourse.processing.org/u/kiraraew)\
**Post date:** [May 21, 2019, 9:44pm UTC](https://discourse.processing.org/t/cant-figure-out-how-to-fix-this-nullpointerexception/11441/7 "2019-05-21T21:44:05Z")

</div>

Okay now I have a new problem arising. I’ve fixed the setup and draw loop to:

```auto
void setup()
{  
  String portName = Serial.list()[6]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);

  ConfigurationBuilder cb = new ConfigurationBuilder();
  cb.setOAuthConsumerKey("---");
  cb.setOAuthConsumerSecret("---");
  cb.setOAuthAccessToken("---");
  cb.setOAuthAccessTokenSecret("---");

  TwitterFactory tf = new TwitterFactory(cb.build());

  twitter = tf.getInstance();
}  

```

```auto
void draw() {
  sensorValue = trim(myPort.readStringUntil('\n'));
  if (sensorValue != null && !sensorValue.isEmpty()) {
    int sensorInt = int(sensorValue);  
    if (sensorInt < 240) {
      tweet();
    }
  }
}

```

But I keep on receiving null values for the sensorValue when before I was receiving the actual data from Arduino. I checked the serial monitor on Arduino to see if the sensor was still working and outputting values, and it was, Processing is just now not giving me those values. I tried all of the ports and used println(Arduino.list()); to check everything, but still no luck. Any possible guesses on how I could fix this issue? Thanks! 🙂

---

<div class="post-metadata">

**Author:** ![jeremydouglass](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jeremydouglass/32/20_2.png) [@jeremydouglass](https://discourse.processing.org/u/jeremydouglass)\
**Post date:** [May 24, 2019, 2:11pm UTC](https://discourse.processing.org/t/cant-figure-out-how-to-fix-this-nullpointerexception/11441/8 "2019-05-24T14:11:07Z")

</div>

Were you able to resolve this issue?

If you revert to an earlier version of the sketch, does that still work? When you print Serial.list(), what does it say? Before you were using 5. Also, always important to unplug / plug when the code is unchanged but communication has stopped.

---

<div class="post-metadata">

**Author:** ![kiraraew](https://avatars.discourse-cdn.com/v4/letter/k/f14d63/32.png) [@kiraraew](https://discourse.processing.org/u/kiraraew)\
**Post date:** [May 24, 2019, 3:16pm UTC](https://discourse.processing.org/t/cant-figure-out-how-to-fix-this-nullpointerexception/11441/9 "2019-05-24T15:16:46Z")

</div>

Hi! Yes I did. I had switched computers, which is why the port number had changed. 🙂 Thank you though! 😁
