Search code examples
javanullpointerexceptionbukkit

I initialized a variable inside of a constructor, but it's still null when I try to use it in another method


So here is the constructor

private ActionbarTitleObject timer = TitleFactory.newBarTitle("");
private Plugin plugin;
HashMap<String, Parkour> parkours = null;

public MineJump() {}

public MineJump(ArrayList<Player> players, String configPath, Plugin plugin)
{
    super(players);
    this.plugin = plugin;
    parkours = Parkour.load(configPath, players);
    System.out.println(parkours.get("p1").getCurrentSpawn()); //here I get the right value
}

but when i try to use the parkours hash map in this Method

@EventHandler
public void onPlayerMove(PlayerMoveEvent e)
{
    System.out.println(parkours.get("p1").getCurrentSpawn()); //parkours is null here :(
}

I get a NullPointerException. Why is that?

I used the non-argument constructor to only to this: Bukkit.getPluginManager().registerEvents(new MineJump(), this);

Could that have caused the error? If yes, it would be nice if you could explain to me why. :)


Solution

  • As you explained, you used your no argument constructor. This constructor does not set parkours to a different value than null.

    You need to use your second constructor with arguments like this:

    Bukkit.getPluginManager().registerEvents(new MineJump(players, configPath, plugin), this);