1

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().

Spooky
  • 315
  • 1
  • 3
  • 12

3 Answers3

5

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.

Community
  • 1
  • 1
Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
  • @Spooky Then it's fine, but can you guarantee that?You shouldn't take such assumptions that might not be true in the future. – Sleiman Jneidi Nov 15 '14 at 15:58
  • Yeah, I know, re-usability, but I don't really understand the way it is done in your link, do I have to change the loader class to an enum ? – Spooky Nov 15 '14 at 16:07
  • @Spooky Exactly, you change to an enum , Watch this if you found it hard to understand https://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s – Sleiman Jneidi Nov 15 '14 at 16:10
  • I understood, I have made some change of course, everything work except that Loader need a string (gameName) to be initialized, but how to pass a parameter to the constructor if I can't access it ? I can't put the gameName field in the enum, there is an error : Syntax error on token "String", strictfp expected – Spooky Nov 15 '14 at 16:28
  • @Spooky Singletons cannot take parameters, I think it's not the right pattern for you. – Sleiman Jneidi Nov 15 '14 at 16:31
  • Yes I know but without the enum I can initialize this field before the instance is created : public static String gameName; – Spooky Nov 15 '14 at 16:33
  • Adding synchronized to the constructor or the instance() method can avoid problem too, am I right ? – Spooky Nov 15 '14 at 17:20
4
public static Loader instance() {
    if (instance == null) {
        instance = new Loader();
        System.out.println("Loader ready");
    }
    return instance;
}

You forgot to asign your instance variable

Anthony Raymond
  • 7,434
  • 6
  • 42
  • 59
2

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

if (instance == null) {
    instance = new Loader();
    System.out.println("Loader ready");
}
SMA
  • 36,381
  • 8
  • 49
  • 73