Why am I getting this NPE?

Discussion in 'Spigot Plugin Development' started by DotRar, Apr 17, 2017.

  1. I have this method for scoreboards:
    Code (Text):
    public void update(Player p) {
            if(!boards.containsKey(p)) boards.put(p, Bukkit.getScoreboardManager().getNewScoreboard());
            Scoreboard board = boards.get(p);
            Objective o = board.getObjective(DisplaySlot.SIDEBAR);
            if(o == null) o = board.registerNewObjective(p.getName(), "dummy"); //NPE is given by this line

            for(String s : board.getEntries()) board.resetScores(s);
            o.getScore("§aOnline Players: §6"+Bukkit.getOnlinePlayers().size()).setScore(5);
            o.getScore(ChatColor.AQUA+"").setScore(4);
            o.getScore("§aKills: §6"+stats.getKills(p.getUniqueId().toString())).setScore(3);
            o.getScore("§aDeaths: §6"+stats.getDeaths(p.getUniqueId().toString())).setScore(2);
            o.getScore(ChatColor.RED+"").setScore(1);
            o.getScore("§aKillstreak: §6"+ StreakManager.INSTANCE.getStreak(p)).setScore(0);

            boards.put(p, board);

            p.setScoreboard(board);
        }
    but for some reason, my null check is giving me an NPE. Why could this be happening?
     
  2. Either board or player is null. Check these variables
     
  3. Mas

    Mas

    It will have to be the player, since Board#getObjective is used on the previous line with no error,
     
    • Agree Agree x 1
  4. Neither can be. Board is created at the top of the method and it's give to the player on death (obviously the player must exist)
     
  5. Mas

    Mas

    Are you sure it's that line the error is given on?
     
  6. Yes
     
  7. Well this is very weird then, because ItsMas_ is correct, the player variable will probably be the problem (or you didn't define you board correct for some reason), try to add debug messages, then try to use the board with another player which is still alive and you know exists (for example yourself), then see if the error still consists!
     
  8. @DotRar it's the only variable that could even be null, so debug it.

    Also,
    • Instead of containsKey & put, use computeIfAbsent
    • The last put call doesn't do anything, since the value is already in the Map (and it's mutable, so already up to date)
    • Use ChatColor instead of section signs
    • Don't use stringified UUIDs, use UUIDs themselves (it's better for performance, less error-prone, etc)
     
    • Like Like x 1
    • Agree Agree x 1