[LibGDX] NullPointerException and batch

Hi ;D

I’m trying to make a simple tile mapping but I have a problem with the rendering. I have a NullPointer exception :frowning:


Caused by: java.lang.NullPointerException
	at Map.render(Map.java:51)
	at .render(LabC.java:47)

I use 3 classes :

  • Block => Each Tile
  • Map => two dimensional “Block” array
  • LabC => The main class

For rendering one Block I use this function:

Block.java:

public void render(){
// "sprite" is a Sprite object for Texture, position ... of the Tile.
		sprite.draw(LabC.batch);
	}

To display all tiles I use this function:
Map.java

public void render(){
		for(int y = 0;y < map.length; y++){
			for(int x =0;x < map[1].length; x++){
				blockmap[x][y].render();
			}
		}
	}

And the render method :

LaboC.java

public static SpriteBatch batch;
...
public void render() {		
		Gdx.gl.glClearColor(0, 0, 0, 1);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		batch.setProjectionMatrix(camera.combined);
		
		batch.begin();
		test.render();
//"test" is a Map object
		batch.end();
	}

Thx for the help

it must be an initialization problem, make sure you initialize all your variable before using them .
good luck

public void render(){
// "sprite" is a Sprite object for Texture, position ... of the Tile.
      LabC.batch.begin();
      sprite.draw(LabC.batch);
      LabC.batch.end();
   }

That’s your solution, I’m pretty sure. I’m not too keen on your use of statics for this, but I think that should work.

Make sure you initialize everything in the create() method instead of statically in the class “header”.

Full code of LabC class.

Would passing an instance of Map (or maybe just blockmap[][]) to LaboC so it could be rendered there be a better solution (given of course that it makes sense considering the TS’s code overall)?

I fix my problem !
Appently my inititalization wasn’t good
Thx for the help