Problem while cancelling BlockPlaceEvent

Discussion in 'Spigot Plugin Development' started by Zendovo, Sep 30, 2018.

Thread Status:
Not open for further replies.
  1. Hey there, so following is my code which is supposed to cancel the BlockPlaceEvent if the item contains a specific lore and it very well does IF the item isn't being removed the second it is right clicked. The plugin is supposed to remove the skull when the skull is clicked. So, when the skull is right clicked the item is removed and there is no item in hand to be checked for which results in a NullPointerException. Is there a way around this?


    Code (Java):
        public void onSkullPlace(BlockPlaceEvent e) {
            Player p = e.getPlayer();
            Block block = e.getBlock();
            ItemStack item = p.getItemInHand();
            if (block.getType() == Material.SKULL) {
            List<String> lore = item.getItemMeta().getLore();
            if (lore != null) {
            for (String key : config.getConfigurationSection("apples").getKeys(false)) {
                if (lore.contains(ChatColor.translateAlternateColorCodes('&', config.getString("apples." + key + ".ilore")))) {
                    e.setCancelled(true);
                    }
                }
            } else {
                e.setCancelled(false);
                return;
            }
        }
        }
     
  2. if(block == null){
    return;
    }
     
  3. I can't do that because when the item is removed the block is placed as well.
     
  4. Thanks for helping!

    I fixed it by adding a try and catch.

    If anyone is wondering what I did, here is my code. I will keep the thread open for a few minutes, maybe there is a better way to achieve it. :)

    Code (Java):
            try {
                item.getItemMeta().getLore();
            } catch (NullPointerException npe) {
                e.setCancelled(true);
                return;
            }
     
    • Funny Funny x 1
    • Friendly Friendly x 1
  5. No please no. STop
     
    • Agree Agree x 1
  6. Alright :ROFLMAO:
    I will close the thread.
    Anyways, @Alex0589 your reply kinda helped. Kinda. :p
     
Thread Status:
Not open for further replies.