1.8.8 NullPointerException

Discussion in 'Spigot Plugin Development' started by Deagan, Apr 13, 2020.

  1. Hello, I'm new to coding in java and i've come across a nullpointerexception on line 44
    Code (Java):

    if (!p.getInventory().getItemInHand().getItemMeta().getDisplayName().equalsIgnoreCase((ChatColor.GOLD + "Golden Head"))) {
            return;
        }
     
    I have no idea why it is doing this.

    Full Code:
    Code (Java):

    package com.shintopractice.gheads;

    import java.util.Arrays;
    import java.util.HashMap;

    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.Action;
    import org.bukkit.event.player.PlayerInteractEvent;
    import org.bukkit.scheduler.BukkitRunnable;



    public class GHeadListener implements Listener {
       
       
    private HashMap<Player, Integer> cooldownTime;
    private HashMap<Player, BukkitRunnable> cooldownTask;
       
       
    @EventHandler
    public void onHeadeat(PlayerInteractEvent e) {
       
    Player p = e.getPlayer();
    Action a = e.getAction();




    if(a == Action.LEFT_CLICK_AIR | a == Action.LEFT_CLICK_BLOCK | a == Action.RIGHT_CLICK_AIR | a == Action.RIGHT_CLICK_BLOCK) {
       
        if (p.getInventory().getItemInHand() == null) {
            return;
        }

        if (!p.getInventory().getItemInHand().hasItemMeta()) {
            return;
        }
       
       
        if (!p.getInventory().getItemInHand().getItemMeta().getDisplayName().equalsIgnoreCase((ChatColor.GOLD + "Golden Head"))) {
            return;
        }
         
        else {
            p.sendMessage(ChatColor.GREEN + "You ate a head!");
        }
       
        }

    }

    }

     
    Any help is greatly appreciated!
     
  2. drives_a_ford

    Moderator

  3. Displayname can be null too. If no custom name was set AFAIK.
    Iirc setting displayname to null would make the default name appear.
     
  4. drives_a_ford

    Moderator

    You're right. In legacy versions such as 1.8.8, this is still the case (source).

    I didn't mention it because it is not the case in the current software, where ItemMeta#getDisplayName cannot be null (according to the linked javadocs as well as the source and the method it uses).
     
  5. Oh i didn't know it was changed. Gotta update my own code than.
    But than nothing else should cause a NPE. He already has a check for the item meta and if player or inventory where null the exception would have occurred earlier in the code.

    Edit: he has the 1.8 tag so it is probably the displayname