InventoryCloseEvent fired 3 times

Discussion in 'Spigot Plugin Development' started by Arman, Jun 22, 2015.

  1. Hello,

    I'm trying to add all items from a specific inventory to the player's inventory when they close it:

    Code (Java):
        public void onClose(InventoryCloseEvent e) {
            if (e.getInventory().equals(inv)) {
            for (ItemStack item : e.getInventory().getContents()) {
                if (item != null) {
    Seems like it should work, right? The problem seems to be, the event is fired three times (twice when inv is opened, once when inv is closed), resulting in the items being added to the inventory three times. (I added a debug message after checking if the inventory is inv. After closing inv, the debug message is displayed three times. This is odd, because the event fires once with other inventories.

    Inv is opened when a player clicks a specific block (InventoryCloseEvent is fired twice here). closeInventory() is not called anywhere in my code. The only other time inv is accessed is when the block is clicked, which is when the title, size, and items of inv are set, and the inventory is opened for the player.

    What could be causing this?

  2. Maybe other code is bothering this?
  3. Here's the whole class, pretty much the PlayerInteractEvent and the command management (which shouldn't affect anything):
  4. I might be super idiotic here, but shouldn't you return?
  5. If you mean return at the debug message, i've done so before uploading to HasteBin, the message has still been displayed three times. If you mean return after adding the items to the inventory, why?
  6. Return at the debug-message. Shouldn't it be
    Code (Text):
            if (e.getInventory().equals("inv")) {
  7. No, inv is the name of my inventory variable.
  8. Oh, lol. I really don't know what the issue is.
  9. Your code is an absolute mess. What may be happening here is that you open the inventory multiple times, which closes the current inventory, resulting in firing the InventoryCloseEvent. Take a look at your method for opening.
  10. Oh, the stuff I miss... just had to add a break after opening the inventory. Thanks for pointing out that the code isn't clean, what would you recommend for cleaning it up?
  11. Setting fields, organizing code, etc etc.
  12. Are you running the latest build, maybe it's a bug?
  13. Using multiple packages / classes, and even javadocs all help to keep code organized -- something that definitely comes with practice. The best part about organized code I think is that it's easily maintainable - both to yourself and others.
  14. Nope, it's fine now, just had to open the inventory either outside of the loop or by breaking the loop. Thank you everyone, i'll be sure to organize everything.