Solved getDisplayName returning null on custom named items

Discussion in 'Plugin Development' started by Scullyking, Jul 3, 2015.

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

    Scullyking

    Here's my method to check if a player's inventory contains x number of a custom named item.

    Code:
        public static boolean containsByName(Player player, String name, Integer amount) {
    
            int qty = 0;
    
            for (ItemStack item : player.getInventory().getContents()) {
                if (item != null && !item.getType().equals(Material.AIR)) {
                    if (item.hasItemMeta() && item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName().equalsIgnoreCase(name)) {
                        qty += item.getAmount();
                    }
                }
            }
    
            return (qty >= amount);
        }
    However it's not getting based the second if statement because hasDisplayname() or hasItemMeta() must be returning null. What's up with this? How can I fix this? Note: it's only a problem with custom named items.
     
  2. Offline

    Synapz

    I cant help but notice your using static on this method... Dont use static just for being able to access it in another class! Bad!
     
  3. Offline

    Scullyking

    @Synapz
    It's a utility function inside a class called InventoryUtils, it's doesn't need to be part of an object.
     
  4. I also get this sort of error. My workaround is instead of using hasItemMeta or hasDisplayName, I check if they're not null.

    E.g.
    Code:
    if (itemStack.getItemMeta() != null && itemStack.getItemMeta().getDisplayName() != null) {
    
    }
    
    Also, if the item name has colours, your method may not work, you need to make sure the colour codes are perfectly accurate. In Bukkit (Spigot 1.8), I believe if you set the sign line 1 to "&0[&1Hi&0]", it'd return "[&1Hi&0]" and not "&0[&1Hi&0]" which is one weird thing.
     
    Scullyking likes this.
  5. Offline

    Scullyking

    @KingFaris11

    Thanks! Totally forgot about the ChatColor thing!
     
Thread Status:
Not open for further replies.

Share This Page