Spooky
Spooky

Reputation: 355

Getting a weird null pointer exception

I get a null pointer exception at this line :

private ArrayList<DrawableEntity> entitiesToDraw = Loader.instance().getDrawableEntities();

There is apparently no problem with the constructor of Loader :

public static Loader instance() {
    if (instance == null) {
        new Loader();
        System.out.println("Loader ready");
    }
    return instance;
}

Because I get the message "Loader ready". I don't understand, the problem seem to be before the call to getDrawableEntities() but I see nothing and it is not inside getDrawableEntities().

Upvotes: 1

Views: 97

Answers (3)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23319

You forgot to assign it to instance

   public static Loader instance() {
      if (instance == null) {
        instance = new Loader();
        System.out.println("Loader ready");
       }
     return instance;
   }

And by the way, if thats a singleton then it's wrong (not thread-safe), Here's a way to implement the singleton pattern.

Upvotes: 5

SMA
SMA

Reputation: 37023

You are not setting instance value when its null. It should be:

if (instance == null) {
    instance = new Loader();
    System.out.println("Loader ready");
}

Upvotes: 2

Anthony Raymond
Anthony Raymond

Reputation: 7862

public static Loader instance() {
    if (instance == null) {
        instance = new Loader();
        System.out.println("Loader ready");
    }
    return instance;
}

You forgot to asign your instance variable

Upvotes: 4

Related Questions