Get ItemMeta from inventory

Discussion in 'Spigot Plugin Development' started by ShalaRD, May 21, 2016.

  1. Code (Text):
            for (ItemStack inven : p.getInventory().getContents()) {
                if (!inven.getItemMeta().getDisplayName().equals("Diamond Sword")) {
                    pi.addItem(new ItemStack(Material.DIAMOND_SWORD));

    Please help...
  2. What is the error.
  3. Code (Text):
            at daniel.Commands.Repair.Fighter( ~[?:?]
            at daniel.Commands.Repair$ ~[?:?]
            at ~[spigot.jar:git-Spigot-db6de12-18fbb24]
            at org.bukkit.craftbukkit.v1_8_R3.scheduler.CraftScheduler.mainThreadHeartbeat( [spigot.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.MinecraftServer.B( [spigot.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.DedicatedServer.B( [spigot.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.MinecraftServer.A( [spigot.jar:git-Spigot-db6de12-18fbb24]
            at [spigot.jar:git-Spigot-db6de12-18fbb24]
            at Source) [?:1.8.0_73]
    line 41 is the error
  4. You should check if there is a ItemMeta present and then if it has a Display Name. And for your purpose i would advise to check the Material not the Display Name of the Item. That is way more better and less code
  5. if i will do Material its will not work when its having on the sword enchantment....
  6. You need to check if the item isn't null before trying to use it, if the item has ItemMeta before trying to use it, and if the item has a display name before trying to use it.
  7. In my experience not checking that ItemMeta is present has never created issues, checking for display name is a definite though.
  8. Just fixed it:
    Thanks for who tried to help me...
    Code (Text):
            if (p.getInventory().contains(Material.DIAMOND_SWORD)) {
                p.sendMessage("You already having DIAMOND_SWORD");
                return true;
            } else {
                p.getInventory().addItem(new ItemStack(Material.DIAMOND_SWORD));
                return true;
  9. mark as solved bud.
  10. Just for the sake of helping potential future readers, mind sharing some snippets where not checking does cause problems?

    I only see potential for it to go wrong when the Material is null, then it can't be generated.
    #12 smrkn, May 27, 2016
    Last edited: May 27, 2016
  11. @Mesmerised i viewed into my Code and it does'nt need ItemStack#hasItemMeta but for Displayname, Lore etc. Also ItemMeta#hasDisplayName or ItemMeta#hasLore
  12. What do you mean ?