Solved NullPointerException with kicking players

Discussion in 'Spigot Plugin Development' started by usernameissexy1, Mar 30, 2020.

  1. Im making a punishment plugin just for the fun of being in isolation...

    Most of the plugin works (the parts ive made lmao) and when i go to ban a player which just kicks them atm, it works fine until I try to "ban" and offline player and it gives a NPE where i check if the player is online.

    https://pastebin.com/SNggiviy
    https://pastebin.com/NBzYgK5U

    Thanks :)
     
  2. What I can think of rn is that `PunishManager.getPlayer(player)` returns a null. Maybe try debugging this part of your code.
     
  3. Yeah, its an issue with the getPlayer() function... https://pastebin.com/ujfrtFzq mind if you could help with solving it?
     
  4. The code is inconsistent here, in this you call `PunishManager.getPlayer(player)` but here you only have the method `PunishManager.getPlayer()`
     
  5. forgot i removed it to test, I removed the Player from it cause it was useless
     
  6. When using your ban method you need an Object of type Player. When calling a Player he can never be offline unless you want to get a NullPointerException. If you want to ban a player which is offline you should either use his Name (save ban as a String) or you use the UUID (highly recommended).

    When checking if the player is online I would also recommend using his uuid. That way you most likely will rarely see any NullPointerExceptions.
     
  7. Alright, I changed the getPlayer() function and made it so it returns a UUID, then i have changed the way i checked if the player is online, I used "Bukkit.getOfflinePlayer(UUID).isOnline()" and now everything works with no errors or NPE's thanks guys :)
     
  8. A little word of advice, always wrap `kickPlayer()` in the scheduler `runTask()` method. This will prevent errors down the line, especially if you kick a player while changes are being made.
    Code (Text):
    plugin.getServer().getScheduler().runTask(plugin, new Runnable() {
        public void run() {
       
        }
    });
    Happy developing!