Search code examples
javaandroidlibgdxtileregion

TiledMapTile set texture region gives NullPointerException


I'm having some trouble with setting texture region to my TiledMapTile. It gives me NullPointerException and I have no idea why.

Here is some code:

TiledMapTile coinTile;

public void show () {
    mapTexture1 = new Texture(Gdx.files.internal("maps/other/texture1.png"));

    TextureRegion mapTexture1Region = new TextureRegion(mapTexture1, 32, 0, 16, 16);
    coinTile.setTextureRegion(mapTexture1Region);
}

And here is the error:

04-09 21:57:18.222: E/AndroidRuntime(7792): java.lang.NullPointerException
04-09 21:57:18.222: E/AndroidRuntime(7792): at com.never.mind.screens.GameScreen.show(GameScreen.java:225)

which leads to this line:

coinTile.setTextureRegion(mapTexture1Region);

Solution

  • Usually, a NullPointerException happens when you did not initialize something in your code.

    Since you did not provide your full code, I could only give your suggestions. Like what you did

    mapTexture1 = new Texture(Gdx.files.internal("maps/other/texture1.png"));
    

    You should also

    coinTile = new TiledMapTile () {
    @Override
    public int getId() {
        return 0;
    }
    
    @Override
    public void setId(int id) {
    
    }
    
    @Override
    public BlendMode getBlendMode() {
        return null;
    }
    
    @Override
    public void setBlendMode(BlendMode blendMode) {
    
    }
    
    @Override
    public TextureRegion getTextureRegion() {
        return null;
    }
    
    @Override
    public void setTextureRegion(TextureRegion textureRegion) {
    
    }
    
    @Override
    public float getOffsetX() {
        return 0;
    }
    
    @Override
    public void setOffsetX(float offsetX) {
    
    }
    
    @Override
    public float getOffsetY() {
        return 0;
    }
    
    @Override
    public void setOffsetY(float offsetY) {
    
    }
    
    @Override
    public MapProperties getProperties() {
        return null;
    }
    
    }
    

    By the way read the API for spcific paremeters.

    Since you are new to java read here to get a grasp of NullPointers