Solved NullInstancePointer

Discussion in 'Plugin Development' started by Kassestral, Feb 28, 2015.

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

    Kassestral

    I'm having a rather odd issue when getting my instance of my main class, for some reason when I have made all of my previous command classes it has worked perfectly, but for some reason it will not work with my new class.

    The only difference I noticed is that 'import com.kassestral.plugins.imperium.Plugin;' is not imported in my new class, so I manually imported it, but still it returns nullPointerException on 'plugin.Log("alright?");'

    Non working (new class)
    Code:
    package com.kassestral.plugins.imperium;
    
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    
    public class Home implements CommandExecutor {
    
        Plugin plugin = Plugin.plugin;
       
        @Override
        public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
            if(command.getName().equalsIgnoreCase("home")) {
                plugin.Log("alright?");
            }
            return false;
        }
    
    }
    One of my other classes (Working)
    Code:
    package com.kassestral.plugins.imperium.commands;
    
    import java.util.HashMap;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    
    import com.kassestral.plugins.imperium.Message;
    import com.kassestral.plugins.imperium.Plugin;
    
    public class Teleport implements CommandExecutor {
    
        Plugin plugin = Plugin.plugin;
        Message message = new Message();
        HashMap<String,String> requests = new HashMap<String, String>();
       
       
        @SuppressWarnings("deprecation")
        @Override
        public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
           
            if(command.getName().equalsIgnoreCase("tpa")) {
                if(sender instanceof Player) {
                    Player player = (Player) sender;
                   
                    if(args.length == 1) {
                        Player target = Bukkit.getServer().getPlayerExact(args[0]);
                       
                        if(target != null) {
                            if(requests.containsValue(target.getName())) {
                                requests.remove(target.getName());
                                requests.put(target.getName(), player.getName());
                                player.sendMessage(ChatColor.LIGHT_PURPLE + "You have sent a teleport request to " + ChatColor.WHITE + target.getName());
                                target.sendMessage(ChatColor.LIGHT_PURPLE + "You have recieved a teleport request from " + ChatColor.WHITE + player.getName());
                            }
                            else {
                                requests.put(target.getName(), player.getName());
                                player.sendMessage(ChatColor.LIGHT_PURPLE + "You have sent a teleport request to " + ChatColor.WHITE + target.getName());
                                target.sendMessage(ChatColor.LIGHT_PURPLE + "You have recieved a teleport request from " + ChatColor.WHITE + player.getName());
                            }
                        }
                        else {
                            player.sendMessage(message.offlinePlayer());
                        }
                    }
                    else {
                        player.sendMessage(ChatColor.RED + "Usage: /tpa <playername>");
                    }
                }
                else {
                    plugin.Log("This command cannot be executed from the console");
                }
            }
           
            else if(command.getName().equalsIgnoreCase("tpaccept")) {
                if(sender instanceof Player) {
                    Player player = (Player) sender;
                   
                    if(requests.containsKey(player.getName())) {
                        Player target = (Player) Bukkit.getServer().getPlayerExact(requests.get(player.getName()));
                        requests.remove(player.getName());
                        if(target != null) {
                            if(target.isOnline()) {
                                target.teleport(player);
                                player.sendMessage(ChatColor.LIGHT_PURPLE +"You have " + ChatColor.GREEN + "ACCEPTED "+ ChatColor.WHITE + target.getName()+"'s" + ChatColor.LIGHT_PURPLE +" teleport request");
                                target.sendMessage(ChatColor.WHITE + player.getName() + ChatColor.LIGHT_PURPLE +" has " + ChatColor.GREEN + "ACCEPTED"+ ChatColor.LIGHT_PURPLE +" your teleport request");
                            }
                            else {
                                player.sendMessage(message.offlinePlayer());
                            }
                        }
                        else {
                            player.sendMessage(message.offlinePlayer());
                        }
                    }
                    else {
                        player.sendMessage(ChatColor.RED + "You do not have any teleport requests");
                    }
                }
                else {
                    plugin.Log("This command cannot be executed from the console");
                }
            }
           
            else if(command.getName().equalsIgnoreCase("tpdeny")) {
                if(sender instanceof Player) {
                    Player player = (Player) sender;
                   
                    if(requests.containsKey(player.getName())) {
                        Player target = (Player) Bukkit.getServer().getPlayerExact(requests.get(player.getName()));
                        requests.remove(player.getName());
                       
                        if(target != null) {
                            if(target.isOnline()) {
                                player.sendMessage(ChatColor.LIGHT_PURPLE +"You have " + ChatColor.RED + "DENIED "+ ChatColor.WHITE + target.getName()+"'s" + ChatColor.LIGHT_PURPLE + " your teleport request");
                                target.sendMessage(ChatColor.WHITE + player.getName() + ChatColor.LIGHT_PURPLE +" has " + ChatColor.RED + "DENIED"+ ChatColor.LIGHT_PURPLE +" teleport request");
                            }
                            else {
                                player.sendMessage(message.offlinePlayer());
                            }
                        }
                        else {
                            player.sendMessage(message.offlinePlayer());
                        }
                    }
                    else {
                        player.sendMessage(ChatColor.RED + "You do not have any teleport requests");
                    }
                }
            }
           
            return false;
        }
       
    }
     
  2. @Kassestral Please post the "Plugin" class, if you need to access a class do so by passing the instance through the constructor.
     
  3. Offline

    Kassestral

    @bwfcwalshy
    I also tried using a constructor, however it still returns a nullPointerException.
    I know most people say not to use a public static variable for getting instances, but it's always worked fine for me in the past.

    Plugin.class
    Code:
    package com.kassestral.plugins.imperium;
    
    import java.io.File;
    import java.io.IOException;
    
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.entity.EntityType;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import com.kassestral.plugins.imperium.commands.*;
    import com.kassestral.plugins.imperium.events.*;
    
    public class Plugin extends JavaPlugin {
       
        public static Plugin plugin;
        private File economy_directory = new File(this.getDataFolder() + File.separator + "accounts");
        private File configuration_file = new File(this.getDataFolder() + File.separator + "config.yml");
        private YamlConfiguration configuration = YamlConfiguration.loadConfiguration(configuration_file);
       
        // Command Classes
        private Teleport teleport = new Teleport();
        private Msg msg = new Msg();
        private Pay pay = new Pay();
        private Balance balance = new Balance();
        private Home home = new Home();
       
        public void onEnable() {
            plugin = this;
            try {
                onStart();
                cleanEvents();
                cleanCommands();
                } catch (IOException e) {
                    e.printStackTrace();
                    }
        }
       
        public void onDisable() {
           
        }
       
        private void onStart() throws IOException {
            if(!economy_directory.exists()) {
                economy_directory.mkdirs();
            }
            if(!configuration_file.exists()) {
                configuration_file.createNewFile();
                createConfig();
            }
        }
       
        @SuppressWarnings("deprecation")
        private void createConfig() throws IOException {
           
            configuration.set("starting_balance", 50D);
            for(int i = 50; i > 49 && i < 67; i++) {
                EntityType hostile_type = EntityType.fromId(i);
                configuration.set("mobs."+hostile_type.getName().toLowerCase()+".reward.lowest", 10D);
                configuration.set("mobs."+hostile_type.getName().toLowerCase()+".reward.highest", 20D);
            }
            for(int x = 90; x > 89 && x < 101; x++) {
                EntityType passive_type = EntityType.fromId(x);
                configuration.set("mobs."+passive_type.getName().toLowerCase()+".reward.lowest", 10D);
                configuration.set("mobs."+passive_type.getName().toLowerCase()+".reward.highest", 20D);
            }
            configuration.save(configuration_file);
        }
       
        private void cleanEvents() {
            this.getServer().getPluginManager().registerEvents(new PlayerVersusEntityForCash(), this);
            this.getServer().getPluginManager().registerEvents(new PlayerJoinandLeaveEvent(), this);
            this.getServer().getPluginManager().registerEvents(new Shop(), this);
        }
       
        private void cleanCommands() {
            getCommand("msg").setExecutor(msg);
            getCommand("r").setExecutor(msg);
            getCommand("pay").setExecutor(pay);
            getCommand("tpa").setExecutor(teleport);
            getCommand("tpaccept").setExecutor(teleport);
            getCommand("tpdeny").setExecutor(teleport);
            getCommand("tpaccept").setExecutor(teleport);
            getCommand("tpdeny").setExecutor(teleport);
            getCommand("balance").setExecutor(balance);
            getCommand("home").setExecutor(home);
        }
       
        public static Plugin getPlugin() {
            return plugin;
        }
    
        public YamlConfiguration getConfiguration() {
            return configuration;
        }
       
        public void Log(String message) {
            this.getServer().getLogger().info(message);
        }
    }
     
  4. @Kassestral If you want to use static make it private and make a getInstance method to return that. I'm not really sure why it is returning null.
     
  5. @bwfcwalshy
    Because he's creating instances of those classes before the plugin variable is initialized.
    Code:
    private Teleport teleport = new Teleport();
    private Msg msg = new Msg();
    private Pay pay = new Pay();
    private Balance balance = new Balance();
    private Home home = new Home();
    These should be initialized in onEnable() after the plugin variable has been set.
     
    Datdenkikniet likes this.
  6. Offline

    Kassestral

    @Assist
    My other classes work fine? They do not have any problems, however I will test this theory :)
     
  7. @Kassestral
    It's generally better to pass the main class instance to other classes through their constructors rather than using static.
    Code:
    private Plugin plugin;
    
    public Home(Plugin instance) {
        plugin = instance;
    }
    Code:
    // home variable in main class
    home = new Home(this);
     
  8. Offline

    Kassestral

    @Assist
    So I changed my code and it works fine, I find it odd how I never had this problem with previous command classes which use the plugin instance?

    Updated Code
    Code:
    package com.kassestral.plugins.imperium;
    
    import java.io.File;
    import java.io.IOException;
    
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.entity.EntityType;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import com.kassestral.plugins.imperium.commands.*;
    import com.kassestral.plugins.imperium.events.*;
    
    public class Plugin extends JavaPlugin {
       
        public static Plugin plugin;
        private File economy_directory = new File(this.getDataFolder() + File.separator + "accounts");
        private File configuration_file = new File(this.getDataFolder() + File.separator + "config.yml");
        private YamlConfiguration configuration = YamlConfiguration.loadConfiguration(configuration_file);
       
        public void onEnable() {
            plugin = this;
            try {
                onStart();
                cleanEvents();
                cleanCommands();
                } catch (IOException e) {
                    e.printStackTrace();
                    }
        }
       
        public void onDisable() {
           
        }
       
        private void onStart() throws IOException {
            if(!economy_directory.exists()) {
                economy_directory.mkdirs();
            }
            if(!configuration_file.exists()) {
                configuration_file.createNewFile();
                createConfig();
            }
        }
       
        @SuppressWarnings("deprecation")
        private void createConfig() throws IOException {
           
            configuration.set("starting_balance", 50D);
            for(int i = 50; i > 49 && i < 67; i++) {
                EntityType hostile_type = EntityType.fromId(i);
                configuration.set("mobs."+hostile_type.getName().toLowerCase()+".reward.lowest", 10D);
                configuration.set("mobs."+hostile_type.getName().toLowerCase()+".reward.highest", 20D);
            }
            for(int x = 90; x > 89 && x < 101; x++) {
                EntityType passive_type = EntityType.fromId(x);
                configuration.set("mobs."+passive_type.getName().toLowerCase()+".reward.lowest", 10D);
                configuration.set("mobs."+passive_type.getName().toLowerCase()+".reward.highest", 20D);
            }
            configuration.save(configuration_file);
        }
       
        private void cleanEvents() {
            this.getServer().getPluginManager().registerEvents(new PlayerVersusEntityForCash(), this);
            this.getServer().getPluginManager().registerEvents(new PlayerJoinandLeaveEvent(), this);
            this.getServer().getPluginManager().registerEvents(new Shop(), this);
        }
       
        private void cleanCommands() {
           
            // Command Classes
            Teleport teleport = new Teleport();
            Msg msg = new Msg();
            Pay pay = new Pay();
            Balance balance = new Balance();
            Home home = new Home();
           
            getCommand("msg").setExecutor(msg);
            getCommand("r").setExecutor(msg);
            getCommand("pay").setExecutor(pay);
            getCommand("tpa").setExecutor(teleport);
            getCommand("tpaccept").setExecutor(teleport);
            getCommand("tpdeny").setExecutor(teleport);
            getCommand("tpaccept").setExecutor(teleport);
            getCommand("tpdeny").setExecutor(teleport);
            getCommand("balance").setExecutor(balance);
            getCommand("home").setExecutor(home);
        }
       
        public static Plugin getPlugin() {
            return plugin;
        }
    
        public YamlConfiguration getConfiguration() {
            return configuration;
        }
       
        public void Log(String message) {
            this.getServer().getLogger().info(message);
        }
    }
     
Thread Status:
Not open for further replies.

Share This Page