java.lang.NullPointerException error

Discussion in 'Spigot Plugin Development' started by MaxKrissigo, May 18, 2016.

  1. I understand where my error it, but don't quite understand why it is occurring and how i would go about solving it. Here is the console error:
    Code (Text):
    null
    org.bukkit.command.CommandException: Unhandled exception executing command 'stats' in plugin MainPlugin v1.0
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[spigot.jar:git-Spigot-e6f93f4-935f18b]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) ~[spigot.jar:git-Spigot-e6f93f4-935f18b]
        at org.bukkit.craftbukkit.v1_9_R1.CraftServer.dispatchCommand(CraftServer.java:645) ~[spigot.jar:git-Spigot-e6f93f4-935f18b]
        at net.minecraft.server.v1_9_R1.PlayerConnection.handleCommand(PlayerConnection.java:1350) [spigot.jar:git-Spigot-e6f93f4-935f18b]
        at net.minecraft.server.v1_9_R1.PlayerConnection.a(PlayerConnection.java:1185) [spigot.jar:git-Spigot-e6f93f4-935f18b]
        at net.minecraft.server.v1_9_R1.PacketPlayInChat.a(PacketPlayInChat.java:45) [spigot.jar:git-Spigot-e6f93f4-935f18b]
        at net.minecraft.server.v1_9_R1.PacketPlayInChat.a(PacketPlayInChat.java:1) [spigot.jar:git-Spigot-e6f93f4-935f18b]
        at net.minecraft.server.v1_9_R1.PlayerConnectionUtils$1.run(SourceFile:13) [spigot.jar:git-Spigot-e6f93f4-935f18b]
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_92]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_92]
        at net.minecraft.server.v1_9_R1.SystemUtils.a(SourceFile:45) [spigot.jar:git-Spigot-e6f93f4-935f18b]
        at net.minecraft.server.v1_9_R1.MinecraftServer.D(MinecraftServer.java:721) [spigot.jar:git-Spigot-e6f93f4-935f18b]
        at net.minecraft.server.v1_9_R1.DedicatedServer.D(DedicatedServer.java:400) [spigot.jar:git-Spigot-e6f93f4-935f18b]
        at net.minecraft.server.v1_9_R1.MinecraftServer.C(MinecraftServer.java:660) [spigot.jar:git-Spigot-e6f93f4-935f18b]
        at net.minecraft.server.v1_9_R1.MinecraftServer.run(MinecraftServer.java:559) [spigot.jar:git-Spigot-e6f93f4-935f18b]
        at java.lang.Thread.run(Thread.java:745) [?:1.8.0_92]
    Caused by: java.lang.NullPointerException
        at me.MaxKrissigo.MainPlugin.Commands.onCommand(Commands.java:43) ~[?:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[spigot.jar:git-Spigot-e6f93f4-935f18b]
        ... 15 more
     
    Here is my commands class:
    Code (Text):
    package me.MaxKrissigo.MainPlugin;

    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.OfflinePlayer;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.Plugin;

    public class Commands implements CommandExecutor {
     
        private StatsInventory statsinventory;
        public String name;
     
        public void onEnable() {
            statsinventory = new StatsInventory((Plugin) this);
        }
     
         static final class name {
             public static String name;
           
         }
     
         public boolean onCommand(CommandSender sender, Command command,
                    String commandLabel, String[] args) {
        if (command.getName().equalsIgnoreCase("stats") && sender.hasPermission("mainplugin.stats")) {
         
            Player p = (Player) sender;
         
            if (args.length == 0) {
             
                p.sendMessage("You must specify a player!");
             
            } else if (args.length == 1) {
                name = args[0];
             
                OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]);
                if (player.hasPlayedBefore()){

                    statsinventory.show(p.getPlayer());
                 
                } else {
                 
                    p.sendMessage(ChatColor.RED + name + " has never joined the server!");
                 
                }
            }
        }
        return true;
         }
       
    }
     
    Statsinventory class:
    Code (Text):
    package me.MaxKrissigo.MainPlugin;

    import java.util.Arrays;

    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.SkullType;
    import org.bukkit.entity.Entity;
    import org.bukkit.entity.Player;
    import org.bukkit.event.Listener;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.PlayerInventory;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.inventory.meta.SkullMeta;
    import org.bukkit.plugin.Plugin;

    import me.MaxKrissigo.MainPlugin.Commands.name;

    public class StatsInventory implements Listener {
     
        private Inventory stats;
        private ItemStack killss, deathss, killstreaks, skullstats, currentkillstreaks, kdrss;
     
     
        public StatsInventory(Plugin p) {
         
            String uuid = ((Entity) p).getUniqueId().toString();
         
            int killssint = Main.config.getInt("Players." + uuid + ".Kills");
            int deathssint = Main.config.getInt("Players." + uuid + ".Deaths");
            int KillStreaksint = Main.config.getInt("Players." + uuid + ".BestKillStreak");
            int CurrentKillStreakint = Main.config.getInt("Players." + uuid + ".CurrentKillStreak");
            double kdr = (double)killssint/deathssint;
         
            stats = Bukkit.getServer().createInventory(null, 27, name.name + "'s Stats");
         
            deathss = createItemds(deathssint, ChatColor.RED + "Deaths");
            killss = createItemks(killssint, ChatColor.RED + "Kills");
            killstreaks = createItemkss(KillStreaksint, ChatColor.RED + "Best Kill Streak");
            currentkillstreaks = createItemkcss(CurrentKillStreakint, ChatColor.RED + "Current Kill Streak");
            kdrss = createItemkdrs(kdr, ChatColor.RED + "KDR");
            skullstats = createItemStatsSkull(name.name);
         
            stats.setItem(4, skullstats);
            stats.setItem(11, killss);
            stats.setItem(13, kdrss);
            stats.setItem(15, deathss);
            stats.setItem(21, killstreaks);
            stats.setItem(23, currentkillstreaks);
         
        }
     
        Player p;
        public void show(Player pl){
            p = pl; //p is no longer null, unless the method show(null) is called, otherwise, you're good to go!
            pl.openInventory(stats);
        }

        PlayerInventory pi = p.getInventory();
     
        private ItemStack createItemds(Integer deathssint, String name) {
         
            ItemStack i = new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal());
            SkullMeta meta1 = (SkullMeta) i.getItemMeta();
            meta1.setOwner("Skeleton");
            meta1.setDisplayName(ChatColor.LIGHT_PURPLE + name);
            meta1.setLore(Arrays.asList(ChatColor.GOLD + "" + deathssint + " Deaths"));
            i.setItemMeta(meta1);
            return i;  
    }
        private ItemStack createItemks(Integer killssint, String name) {
            ItemStack i = new ItemStack(Material.DIAMOND_SWORD, 1);
            ItemMeta im = i.getItemMeta();
            im.setDisplayName(name);
            im.setLore(Arrays.asList(ChatColor.GOLD + "" + killssint + " Kills"));
            i.setItemMeta(im);
            return i;
    }
        private ItemStack createItemkss(Integer killstreaksint, String name) {
            ItemStack i = new ItemStack(Material.DIAMOND_AXE, 1);
            ItemMeta im = i.getItemMeta();
            im.setDisplayName(name);
            im.setLore(Arrays.asList(ChatColor.RESET + "Best Kill Streak " + killstreaksint));
            i.setItemMeta(im);
            return i;
    }
        private ItemStack createItemStatsSkull(String name) {
            ItemStack i = new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal());
            SkullMeta meta1 = (SkullMeta) i.getItemMeta();
            meta1.setOwner(name);
            meta1.setDisplayName(ChatColor.LIGHT_PURPLE + name);
            i.setItemMeta(meta1);
            return i;  
    }
        private ItemStack createItemkcss(Integer killstreaksint, String name) {
            ItemStack i = new ItemStack(Material.DIAMOND_AXE, 1);
            ItemMeta im = i.getItemMeta();
            im.setDisplayName(name);
            im.setLore(Arrays.asList(ChatColor.RESET + "Best Kill Streak " + killstreaksint));
            i.setItemMeta(im);
            return i;
    }
        private ItemStack createItemkdrs(Double kdr, String name) {
            ItemStack i = new ItemStack(Material.DIAMOND_AXE, 1);
            ItemMeta im = i.getItemMeta();
            im.setDisplayName(name);
            im.setLore(Arrays.asList(ChatColor.GOLD + "" + kdr));
            i.setItemMeta(im);
            return i;
    }
     

    }
     
     
  2. Line 46 please.
     
  3. I think you meant line 43?
    Code (Text):
            } else if (args.length == 1) {
                name = args[0];
               
                OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]);
                if (player.hasPlayedBefore()){

                    statsinventory.show(p.getPlayer());//line 43
                   
                } else {
                    //line 46
                    p.sendMessage(ChatColor.RED + name + " has never joined the server!");
                   
                }
     
  4. Yeah sorry 43
     
  5. I think it maybe because of line 43 returning null so maybe check if it is a player first.
     
  6. The object 'p' is null it seems
     
  7. You are most likely not calling onEnable in your Commands class.
    Code (Text):
    public void onEnable() {
            statsinventory = new StatsInventory((Plugin) this);
        }
    This means your initialization code is never being run.

    You should move this into a constructor where is belongs. While you are there you can remove the cast to Plugin which will always fail and actually pass in an instance of your plugin to your newly created constructor.
     
    • Agree Agree x 1
  8. I tried this but got the same error.
    Code (Text):
            } else if (args.length == 1) {
                name = args[0];
               
                OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]);
                if (player.hasPlayedBefore()){
                    if (sender instanceof Player) {
                   
                    statsinventory.show(p.getPlayer());//line 44
                    }
                   
                } else {
                    //line 48
                    p.sendMessage(ChatColor.RED + name + " has never joined the server!");
                   
                }
            }
     
  9. StatsInventory is null, because it never gets assigned to something. Keep in mind that onEnable will only be called in the main class not others.
     
  10. I have called it on onEnable.
     
  11. How would I go about assigning it?
     
  12. Like you did in your onNeable method. Except this method does not get called. Only the onEnable in the main class will get called. Instead move that line to the constructor.
     
  13. If you have called it then you must be ignoring the ClassCastException that it throws when your plugin is being enabled. You can't just cast an object to something it is not. (Commands implementing CommandExecutor is not a Plugin).
     
  14. Always tell people to use @Override.

    Gesendet von meinem Nexus 5 mit Tapatalk
     
    • Agree Agree x 2
  15. You don't have to prefer what almost all people saying is if you don't know how it works.

    @MaxKrissigo there's no need to cast it to plugin looks like

    Code (Java):
    private StatsInventory statsinventory;

    // at on enable

    statsinventory = new StatsInventory(this);
     
  16. You should always use the annotation whenever it is applicable to for the following reasons:
    1. It informs other developers that the method is being overridden in the subclass
    2. The compiler will tell you that the method doesn't exist (typos, missing parameters, etc.)
    3. Using annotations is a good habit to get into, it's as useful as a comment to other developers reading your code
     
    #16 Msrules123, May 19, 2016
    Last edited: May 19, 2016
    • Agree Agree x 2
    • Like Like x 1
  17. then fine :D
     
  18. I can't seem to figure out where to move the line of code. I'm probably doing someone thing really obvious wrong.
     
  19. Do you know what a constructor is/what it's used for? Anyway here's a quick example:
    Code (Text):
    public class Commands {
      public Commands() {
        System.out.println("This constructor gets called when someone does new Commands()");
      public void onEnable() {
        System.out.println("This method gets called when someone does Commands#onEnable()");
      }
    }
    To call the onEnable method of your Commands class you'd have to create an object first and then call the method:
    Code (Text):
    public class ExampleClass {
      public void someMethod() {
        Commands c = new Commands();
        c.onEnable();
      }
    }
    Usually you'd move the code inside your onEnable method inside the constructor so it does get called automatically whenever an object of that class is created. That way you don't have to call an onEnable method seperatly:
    Code (Text):
    public class ExampleClass {
      public void someMethod() {
        Commands c = new Commands();
      }
    }
     
    • Agree Agree x 1
  20. So much misinformation in the thread wow.
     
    • Agree Agree x 1
    • Winner Winner x 1