4
\$\begingroup\$

I am getting a null pointer exception using libGDX that the debugger points as the SpriteBatch.end() line. I was wondering what would cause this.

Here is the offending code block, specifically the batch.end() line:

    batch.begin();

    for (int j = 0; j < 3; j++)
        for (int i = 0; i < 3; i++)
            if (zoomgrid[i][j].getPiece().getImage() != null)
                zoomgrid[i][j].getPiece().getImage().draw(batch);

    batch.end();

The top of the stack is actually a line that calls

lastTexture.bind();

In the flush() method of com.badlogic.gdx.graphics.g2d.SpriteBatch.

I appreciate any input, let me know if I haven't included enough information.

\$\endgroup\$
  • \$\begingroup\$ What type is getImage()? \$\endgroup\$ – XiaoChuan Yu Oct 19 '13 at 3:59
  • \$\begingroup\$ getImage() returns the Sprite member in my Piece class. \$\endgroup\$ – odaymichael Oct 19 '13 at 11:29
  • \$\begingroup\$ How do you set up your Sprite (presuming it's the LibGDX Sprite class)? Sounds a bit like the texture might be null. \$\endgroup\$ – ThorinII Oct 20 '13 at 22:09
  • \$\begingroup\$ I do believe that is it. I was instantiating with new Sprite(),but the draw() method was being called before the texture was actually loaded. Thanks for the response. \$\endgroup\$ – odaymichael Oct 21 '13 at 1:57
2
\$\begingroup\$

The fact that the exception points to a line in the callstack that reads

lastTexture.bind();

allows you to easily determine the cause of the exception (assuming the debug information in accurate and the call stack and exception source data is correct, which is probably a safe assumption in this case).

The only thing that be null in that line is lastTexture. That itself implies that the problem is that you've failed to initialize the sprite object correct, possibly failing to do something that sets up its backing texture (so it's null when you go to render the batch).

\$\endgroup\$
0
\$\begingroup\$

I know, this is old. But since I stumbled upon this issue just recently, I want to add the cause and solution in my case.

In my case this happened, because I used:

val background = TextureRegion()

This empty constructor led to a null texture when flushing the SpriteBatch, after drawing it with:


batch.begin()
batch.draw(background, 0f, 0f, Constant.WIDTHf, Constant.HEIGHTf)
batch.end()

I changed it to the following to prevent this issue:


if(background != null)
{
  batch.begin()
  batch.draw(background, 0f, 0f, Constant.WIDTHf, Constant.HEIGHTf)
  batch.end()
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.