Problem with Nullpointerexception

Asked

Viewed 38 times

0

I got a class like this:

public class TileRender {

    private Map mapa;
    private TileMap tileMap;
    private Tile[] tiles;
    private List<ObjectPointMap> objMap;

    public TileRender(TileMap tileMap, Map mapa) {
        this.mapa = mapa;
        this.tileMap = tileMap;
        this.objMap = new ArrayList<>();

        this.carregarObj();
    }

    public void carregarObj() {

        for(int i=0; i<tileMap.getHeight(); i ++) {
            for(int j=0; j<tileMap.getWidth(); j++) {
                objMap.add(new ObjectPointMap(j * 16, i * 16));
            }
        }
        this.carregarTiles();

    }

    public void carregarTiles() {

        tiles = new Tile[objMap.size()];
        for(int i=0; i<objMap.size(); i++) { 
            BufferedImage image = mapa.getTile((int) (objMap.get(i).getY() / 16), (int) (objMap.get(i).getX() / 16));
            tiles[i] = new Tile(image);
            tiles[i].setPosition(objMap.get(i).getX(), objMap.get(i).getY());
        }
    }

    public void draw(Graphics2D g2d) {

        for(int i=0; i<tiles.length; i++) { 

            //BufferedImage image = mapa.getTile((int) (objMap.get(i).getY() / 16), (int) (objMap.get(i).getX() / 16));
            g2d.drawImage(tiles[i].getImage(), tiles[i].x, tiles[i].y, null);
        }
    }
}

The problem is that when calling the method carregarTiles() both in the constructor and in the load method: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
When inserted in the draw() method, it works.

  • 2

    Call it where? Add the stack of errors and where are you calling this method.

1 answer

1

The problem is due to your objMap is empty when it enters within the method the objMap.size() its size is zero or less

  • But that is impossible.

  • @Eonardo this can be verified in practice in several ways, I’ve thought of a 3. Want to try?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.