Check if item is null (NullPointerException)

Discussion in 'Spigot Plugin Development' started by Lolok, Apr 2, 2019.

    • Like Like x 1
  1. do (item != null && item.getType() != null) that should do the trick! You're trying to check if the type != null, but that is not possible if the ItemStack is null ^^

    Also do not use new String(), just do "".equals this saves memmory :)
     
    • Agree Agree x 1
  2. thanks that work perfetcly

    another issue:
    i'm trying to remove only 10 of heads but plugin remove all heads
    Code (Java):
    ItemStack creeperRemove = item;
    creeperRemove.setAmount(10);

                                        player.getInventory().removeItem(creeperRemove);
     
    • Like Like x 1
  3. Can you please explain what this code has to execute? To give me a better idea what is going on ^^

    btw remove type.getType != null since that would not do anything in this case :eek: it didn't remove when I replied ^^
     
    • Like Like x 1
  4. no it doesn't. its just redundant. null checking the type is useless, it cant be null. check if its air instead.

    youll need to iterate over the inventory again and remove item stacks until you've removed an amount of 10. the last item youll have to set the amount rather than erase it.

    Code (Java):
    for()
    ... first loop
    int amount to remove = 10
    for(same loop)
        if(item equals what u want)
            if(item amount > amount to remove) set item amount to item amount - amount to remove and then break
            else if(item amount == amount to remove) remove item and break
            else amount to remove - item amount and then remove item from inventory
     
  5. thank you for the support
     
    • Like Like x 1
  6. If you're trying to empty an inventory, just use the method Inventory#removeItem(new ItemStack(material, amount));

    Seems you're new to java in general as well as the SpigotAPI, I suggest learning more java before going any further, as it will prevent you from making so many simple mistakes.
    I'd use this as a refference, it includes alot of helpful tips as well as examples:
    https://beginnersbook.com/java-tutorial-for-beginners-with-examples/

    If you're still having trouble feel free to contact me.
     
    • Agree Agree x 1
  7. I will read this, thank you
     
    • Like Like x 1
  8. Or, he could use Inventory#removeItem. It will try to remove x amount of the item, x being whatever amount was set to the ItemStack.
     
  9. i read the documentation and thats what it looked like but i figured that was already being tried and not working. if it works as intended then inventory#removeitem would obv be better
     
  10. :thumbsup: only just realized someone beat me to suggesting it anyways