Solved Null location on InventoryOpenEvent

Discussion in 'Spigot Plugin Development' started by NoKi_Le_Previam, Jan 12, 2020.

  1. Hello hello !

    Sometime it appear a null pointer exception when I use a location from InventoryOpenEvent.

    Here the code :

    Code (Java):
    @EventHandler
    public void onInvOpenEvent(final InventoryOpenEvent event)
    {
        if(event.getInventory().getType() == InventoryType.CHEST)
        {
            String inChestOwner = chestManager.checkInChest(event.getInventory().getLocation());
        }
    }

    public String checkInChest(Location location)
    {
        String key = "" + location.getX() + "|" + location.getY() + "|" + location.getZ(); // Null pointer exception here (sometime)
        if(inChest.get(location.getWorld().getName()).containsKey(key))
        {
            return inChest.get(location.getWorld().getName()).get(key).getPlayerName();
        }
        return null;
    }
    I don't understand. How is it possible?

    Thanks to help me
     
    • Winner Winner x 1
  2. You dont need "chestManager." because you are calling a method from the same class.
    Code (Java):
    String inChestOwner = chestManager.checkInChest(event.getInventory().getLocation());
    Only have it if you were to call the method from another class
     
    • Friendly Friendly x 1
  3. Thanks for your reply but how a chest can be custom created or virtual?? My plugin doesn't do that. Is possible QuickShop plugin does that?

    Thanks for your reply but I just merged methods in same code for this post. checkInChest() method come from an other class. :)
     
  4. Yes, another plugin could create inventories, and then Inventory#getLocation() will return null.
    To avoid the NullPointerException, just add a null check before using your method:
    Code (Java):
    @EventHandler
    public void onInvOpenEvent(final InventoryOpenEvent event)
    {
        if(event.getInventory().getType() == InventoryType.CHEST && event.getInventory().getLocation() != null)
        {
            String inChestOwner = chestManager.checkInChest(event.getInventory().getLocation());
        }
    }
     
    • Winner Winner x 1
  5. Okay thanks for you help :)