Getting state of a block throwing NPE

Discussion in 'Plugin Development' started by MOMOTHEREAL, Feb 1, 2014.

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

    MOMOTHEREAL

    Hello!
    I am doing a simple Sign click thingy for my plugin.
    I am getting an NPE at line 84 of my code, which is:
    Code:
    Sign s = (Sign)b.getState();
    I am using the import: org.bukkit.block.Sign.
    What am I doing wrong here?

    Here is my full code:
    Code:java
    1. @EventHandler
    2. public void signClick(PlayerInteractEvent e) {
    3. Player p = e.getPlayer();
    4. Block b = e.getClickedBlock();
    5. if(b.getState() instanceof Sign){
    6. Sign s = (Sign)b.getState();
    7. if (e.getAction() == Action.RIGHT_CLICK_BLOCK){
    8. if (s.getLine(0) != null && s.getLine(1) != null){
    9. if (s.getLine(0).contains("Kit Selector")) {
    10. if (KitManager.isExisting(s.getLine(1))) {
    11. s.setLine(0, "§1Kit Selector");
    12. KitManager.giveKit(p, s.getLine(1));
    13. } else {
    14. s.setLine(0, "§cKit Selector");
    15. p.sendMessage(Messages.ERR_UNKNOWN_KIT);
    16. }
    17. }
    18. }
    19. }
    20. }
    21.  
    22. }
     
  2. Offline

    adam753

    PlayerInteractEvent is fired when the player left- or right-clicks at all, regardless of whether or not they're looking at a block. Therefore, it's possible for e.getClickedBlock() to return null. To avoid this, you should always check the event's Action enum:

    Code:java
    1.  
    2. @EventHandler
    3. public void signClick(PlayerInteractEvent e) {
    4.  
    5. Action action = e.getAction();
    6.  
    7. if(action == Action.LEFT_CLICK_BLOCK) {
    8. //Safe to do e.getClickedBlock()
    9. }
    10. }
    11.  
     
Thread Status:
Not open for further replies.

Share This Page