Solved HashMap NPE

Discussion in 'Plugin Development' started by thomasb454, Jan 1, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    thomasb454

    Hi, I'm getting an NPE on this line of code:

    if (isOnDuty.get(player.getName())) {

    I'm not very familiar with HashMaps, so if you could point out what I've done wrong that would be great!
     
  2. Offline

    thepaperboy99

    The player is not in the hashmap.
     
  3. Offline

    BillyGalbreath

    Always check if its there before trying to get it.

    Code:java
    1.  
    2. if (isOnDuty.containsKey(player.getName())) {
    3. if (isOnDuty.get(player.getName())) {
    4. // Is on duty
    5. } else {
    6. // Not on duty
    7. }
    8. } else {
    9. // Player not found in hasmap
    10. }
    11.  
     
  4. Offline

    thomasb454


    Ahh, ty. I'll give this a go!
    edit:
    Getting this error:
    The method contains(String) is undefined for the type Map<String,Boolean>
     
  5. Offline

    NinjaWAffles

    Can you post your full code? It's hard to provide help when you aren't giving us much to work with.
     
  6. Offline

    BillyGalbreath

    Change .contains() to .containsKey()
     
  7. Offline

    thomasb454


    Sorry, it's quarter to 6 AM.


    No error, time to test!


    Okay, I got it to semi-work.

    But when I toggle it, from off to on it gives an NPE. Is this because I'm not removing them from the HashMap, code below:

    Code:java
    1. if (!player.hasPermission("prison.guard.dutytoggle")) {
    2. player.sendMessage(Messages.INVALID_PERMSSIONS);
    3.  
    4. } else {
    5. if (isOnDuty.containsKey(player.getName())) {
    6. if (isOnDuty.get(player.getName())) {
    7. isOnDuty.remove(player.getName());
    8. Bukkit.broadcastMessage(Messages.GUARD_TOGGLE_OFF.replaceAll("%guard%", player.getName()));
    9. player.getInventory().clear();
    10. player.getInventory().setArmorContents(null);
    11. } else {
    12. isOnDuty.put(player.getName(), true);
    13. Bukkit.broadcastMessage(Messages.GUARD_TOGGLE_ON.replaceAll("%guard%", player.getName()));
    14. guardKit.giveKit(player);
    15. }
    16. } else {
    17. isOnDuty.put(player.getName(), true);
    18. Bukkit.broadcastMessage(Messages.GUARD_TOGGLE_ON.replaceAll("%guard%", player.getName()));
    19. guardKit.giveKit(player);
    20. }
    21. }
    22. return true;
    23. }
    24. }

    BillyGalbreath

    Bump

    Anyone?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 6, 2016
  8. Offline

    thomasb454

    Title update, this is not a bump. ;)
     
Thread Status:
Not open for further replies.

Share This Page