thunder31
thunder31

Reputation: 117

Java timer error exception

I have a strange error when executing a timertask, what cause it?

public void tick(long milliseconds) {
ctimer = new Timer();
ctimer.schedule(new TimerTask() {
public void run() {
    System.out.println("sec"+sequencer.getMicrosecondPosition()/1000000);           }
}, 0, milliseconds);
}

Error message from command prompt:

Exception in thread "Timer-0" java.lang.NullPointerException
        at MidiTest$1.run(miditest.java:244)
        at java.util.TimerThread.mainLoop(Timer.java:555)
        at java.util.TimerThread.run(Timer.java:505)

Upvotes: 2

Views: 5856

Answers (1)

Augusto
Augusto

Reputation: 29897

I would bet that sequencer.getMicrosecondPosition() returns a Long and it's null. The problem happens because autoboxing/unboxing cannot handle nulls.

edit

Autoboxing is when java transforms a primitive type to it's object wrapper, for example long to Long. You can read more about this feature in these docs.

There's no recipe to fix this, as it depends on what you want to do. Probably you can replace the body of run() with

long position = 0;
if( sequencer.getMicrosecondPosition() != null ) {
    position = sequencer.getMicrosecondPosition();
}

System.out.println("sec" + position/1000000);

which will default the position to 0 if getMicrosecondPosition() is null

Upvotes: 2

Related Questions