bob123456
bob123456

Reputation: 11

Null pointer exception in libgdx

I get the error

Task :desktop: Desktop Launcher. main() FAILED Exception in thread "main" java. lang. Exception In Initializer Error

at com.mygdx.game.Cat.Initextures(Cat.java:23)
at com.mygdx.game.Cat.<init>(Cat.java:20)
at com.mygdx.game.TacoCat.<init>(TacoCat.java:18)
at com.mygdx.game.desktop.DesktopLauncher.main(DesktopLauncher.java:10)

Caused by: java .lang. Null Pointer Exception at com.mygdx.game.Resources.(Resources.java:7) ... 4 more

Caused by: java.lang.NullPointerException

I have two files Resources

package com.mygdx.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;

public class Resources {
    public static Texture catTexture = new Texture(Gdx.files.internal("cat1.png"));
}

Cat

package com.mygdx.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.TextureData;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.Texture;


public class Cat {
    public int x,y,width,height;
    public boolean onGrond;
    public Texture catTexture;
    public Cat(int xpos,int ypos,boolean onGround){
        x = xpos;
        y = ypos;
        this.onGrond = onGround;
        Initextures();
    }
    public void Initextures(){
        catTexture = Resources.catTexture;
        width = Resources.catTexture.getWidth();
        height = Resources.catTexture.getHeight();
    }
    public void draw(SpriteBatch batch){
       batch.draw(catTexture,x,y);
    }

Any help would be amazing and thank you in advance

Upvotes: 1

Views: 784

Answers (1)

bornander
bornander

Reputation: 1158

At the point when catTexture is initialized the Gdx.files member is not yet initialized, so it's null and that is what is causing you problem.

I am guessing that your TacoCat is extending ApplicationAdapter or Application, and you need to override the create method and load your resources (or instanciate your Cat object) in that method.

This is because the libGDX runtime needs to initialize first and things like texture loading must run on the OpenGL thread.

In your TacoCat class don't do this

public class TacoCat extends ApplicationAdapter {
  private Cat cat;

  public TacoCat() {
    cat = new Cat();
  }
}

Do this;

public class TacoCat extends ApplicationAdapter {
  private Cat cat;

  @Override
  public void create() {
    cat = new Cat();
  }
}

Note that you don't have to manually call create, the libGDX runtime will call that for you.

Upvotes: 1

Related Questions