NPE on Inventory Custom contains Method

Discussion in 'Plugin Development' started by BetaNyan, Nov 27, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    BetaNyan

    So I made a shop plugin that is on a sign, and there is a selling feature. The selling feature works, but not with damaged items, and I want damaged items. So I made my own contains method that compares names and not items.

    This is the code

    Code:
    public boolean contains(Player p, ItemStack it, int quanity) {
          if (p.getInventory().getContents().length != 0) {
              p.sendMessage("debug not 0");
              for (ItemStack i : p.getInventory().getContents()) {
                  p.sendMessage("debug loop");
                  if (i.toString().equals(it.toString()) && i.getAmount() >= quanity) {
                      p.sendMessage("debug true");
                      i.setDurability((short)-1);
                      if (quanity != 1) {
                      for (int a=0;a<quanity;a++) {
                          p.getInventory().remove(it);
                          p.updateInventory();
                      }
                      } else {
                          p.getInventory().removeItem(i);
                          p.updateInventory();
                      }
                      return true;
                  } else {
                      p.sendMessage("debug false");
                      continue;
                  }
              }
          }
          return false;
      }
    I get a NPE at "if (i.toString().equals)" line.

    Any reasons why?

    Thanks!
     
  2. Offline

    mythbusterma

    BetaNyan

    Except this doesn't compare names, it compares String representations of ItemStacks, which I'm willing to bet is either its ID or are a re-implementation containing the damage of the item.

    Just compare the Material to a known Material.
     
  3. Offline

    BetaNyan

    I just realized that ItemStack#toString() returns something like id[amount, name] weird thing. I did getType().getString(), but still a NPE.
     
  4. Offline

    Dudemister1999

    BetaNyan mythbusterma What happens when there's an empty space in the inventory? NullPointerException.
     
  5. Offline

    adam753

    BetaNyan
    Bukkit spec is horribly ambiguous when it comes to blank inventory spaces - a blank space can either be Material.AIR, or it can be null. And yes, methods like getContents* will return all the air and null spaces even though that's not what anyone would ever want.

    * I'm not even sure if they all behave this way, I wouldn't be surprised to find there was more ambiguity in here.
     
  6. Offline

    ROTN

    BetaNyan Simply check if the item is not Air or null before running the rest of the code. That would fix at least one error that is [potentially] happening
     
Thread Status:
Not open for further replies.

Share This Page