Why do I keep getting Java.Lang.NullPointerException

204 views Asked by At

I keep getting a Java.Lang.NullPointerException on this code:

private void render(){
    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null){
        this.createBufferStrategy(3);
    }

    Graphics g = bs.getDrawGraphics();

    g.dispose();
    bs.show();
}

Can someone tell what I am doing wrong?

4

There are 4 answers

1
M. Abbas On

You should try this:

private void render(){
    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null){
        this.createBufferStrategy(3);
        bs = this.getBufferStrategy(); // reassign bs
    }

    Graphics g = bs.getDrawGraphics();

    g.dispose();
    bs.show();
}
0
Sergey Kalinichenko On

Even when you call this.createBufferStrategy(3); your bs variable remains unassigned.

You need to read it back after creating it:

if(bs == null){
    this.createBufferStrategy(3);
    bs = this.getBufferStrategy();
}

It is a good idea to add a check to make sure that after the call of createBufferStrategy you get back a non-null:

this.createBufferStrategy(3);
bs = this.getBufferStrategy();
if (bs == null) throw new IllegalStateException("Buffered structure is not created.");
0
Christian Hujer On

You forget to assign the new BufferStrategy in case it was null to the to variable bs. Change it to

if (bs == null) {
    bs = this.createBufferStrategy(3); // in case it returns BufferStrategy.
    bs = this.getBufferStrategy(); // otherwise
}
0
swingBoris On

owww i am so stupid i forgot to put return it should be this

private void render(){
    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null){
        this.createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();

    g.dispose();
    bs.show();
}