Search code examples
javaandroidlibgdx

Libgdx BitmapFont NullPointerException


I created my project with Freetype, tools, and box2d for intellej, and upon trying to run in android studio:

BitmapFont font = new BitmapFont();

it gives me a null pointer exception. I have tried manually putting a font in the assests folder but that did not help. I am able to successfully run the default project (the red background and the picture) but have never successfully ran that line.


Solution

  • Possible reason may be you're initialising local BitmapFont instead of global that you're using in render method.

    public class MyGdxGame extends Game {
    
        Texture texture;
        SpriteBatch spriteBatch;
    
        BitmapFont font;
    
        @Override
        public void create () {
    
            BitmapFont font=new BitmapFont();  // You initialise local, global is still Null
    
            texture=new Texture("badlogic.jpg");
            spriteBatch=new SpriteBatch();
        }
    
        @Override
        public void render() {
            super.render();
    
            Gdx.gl.glClearColor(1,1,1,1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    
            spriteBatch.begin();
            spriteBatch.draw(texture,100,100);
            font.draw(spriteBatch,"HELLO WORLD",100,100); // Now here NPE
            spriteBatch.end();
        }
    }
    

    Default constructor

    BitmapFont font=new BitmapFont();
    

    Internally create two FileHandle one for font file com/badlogic/gdx/utils/arial-15.fnt and another one for imageFile com/badlogic/gdx/utils/arial-15.png. I don't think, it throw NPE may be some other Exception.