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\$
4
  • \$\begingroup\$ What type is getImage()? \$\endgroup\$ Oct 19, 2013 at 3:59
  • \$\begingroup\$ getImage() returns the Sprite member in my Piece class. \$\endgroup\$ Oct 19, 2013 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, 2013 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\$ Oct 21, 2013 at 1:57

2 Answers 2

1
\$\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\$
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\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .