Solved Nullpointer exception drives me nuts

Discussion in 'Plugin Development' started by Larsn, Jun 30, 2015.

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

    Larsn

    I have this code setup in my afCommand.java
    Code:
    if(args[0].equalsIgnoreCase("test")){
          UUID pid = p.getUniqueId();
    (line 126)      plugin.ddata.set(pid.toString() + ".kills", 0);
    }
    But it keeps throwing a nullpointer exception:
    error (open)

    [16:30:07] [Server thread/ERROR]: null
    org.bukkit.command.CommandException: Unhandled exception executing command 'af' in plugin MyPlugin v0.0.1
    at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[Craftbukkit.jar:git-Spigot-"4133000"]
    at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:181) ~[Craftbukkit.jar:git-Spigot-"4133000"]
    at org.bukkit.craftbukkit.v1_8_R1.CraftServer.dispatchCommand(CraftServer.java:643) ~[Craftbukkit.jar:git-Spigot-"4133000"]
    at net.minecraft.server.v1_8_R1.PlayerConnection.handleCommand(PlayerConnection.java:1083) [Craftbukkit.jar:git-Spigot-"4133000"]
    at net.minecraft.server.v1_8_R1.PlayerConnection.a(PlayerConnection.java:918) [Craftbukkit.jar:git-Spigot-"4133000"]
    at net.minecraft.server.v1_8_R1.PacketPlayInChat.a(PacketPlayInChat.java:26) [Craftbukkit.jar:git-Spigot-"4133000"]
    at net.minecraft.server.v1_8_R1.PacketPlayInChat.a(PacketPlayInChat.java:53) [Craftbukkit.jar:git-Spigot-"4133000"]
    at net.minecraft.server.v1_8_R1.PacketHandleTask.run(SourceFile:13) [Craftbukkit.jar:git-Spigot-"4133000"]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_45]
    at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_45]
    at net.minecraft.server.v1_8_R1.MinecraftServer.z(MinecraftServer.java:686) [Craftbukkit.jar:git-Spigot-"4133000"]
    at net.minecraft.server.v1_8_R1.DedicatedServer.z(DedicatedServer.java:316) [Craftbukkit.jar:git-Spigot-"4133000"]
    at net.minecraft.server.v1_8_R1.MinecraftServer.y(MinecraftServer.java:627) [Craftbukkit.jar:git-Spigot-"4133000"]
    at net.minecraft.server.v1_8_R1.MinecraftServer.run(MinecraftServer.java:530) [Craftbukkit.jar:git-Spigot-"4133000"]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_45]
    Caused by: java.lang.NullPointerException
    at me.blabla.moreblabla.commands.afCommand.onCommand(afCommand.java:126) ~[?:?]
    at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[Craftbukkit.jar:git-Spigot-"4133000"]
    ... 14 more


    My main class:
    main.java (open)

    Code:
    package me.Blabla.blabla.core;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Logger;
    
    import org.bukkit.Bukkit;
    import org.bukkit.configuration.InvalidConfigurationException;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import me.Blablabla.commands.afCommand;
    import me.Blablabla.listener.SomeListener;
    
    public class Main extends JavaPlugin {
           
        public final Logger logger = Logger.getLogger("Minecraft");
        public Main plugin;
        public static boolean getDispenserLoc = false;
        public static List<Integer> LocList = new ArrayList<Integer>();
        public static JavaPlugin instance;   
       
        public File DispensersFile = new File(getDataFolder(), "/Data/DispenserLocations.yml");
        public FileConfiguration ddata = YamlConfiguration.loadConfiguration(DispensersFile);
       
        @Override
        public void onEnable(){
            logger.info("Plugin has been enabled!");
            Bukkit.getServer().getPluginManager().registerEvents(new SomeListener(), this);
            getCommand("af").setExecutor(new afCommand());
            this.saveDefaultConfig();
            instance = this;
           
            loadFile(ddata, DispensersFile);
        }
       
        public void loadFile(FileConfiguration ymlConfig, File ymlFile) {
            try {
                    ymlConfig.load(ymlFile);
            } catch (FileNotFoundException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                    e.printStackTrace();
            } catch (InvalidConfigurationException e) {
                    e.printStackTrace();
            }
    }
       
        @Override
        public void onDisable(){
            logger.info("Plugin disabled!");
        }
    
        public void saveFile(FileConfiguration ymlConfig, File ymlFile) {
            try {
                    ymlConfig.save(ymlFile);
            } catch (IOException e) {
                    e.printStackTrace();
            }             
        }
       
    }


    Could someone help me?
     
  2. Offline

    Xerox262

    Could be because it's not finding the uuid + ".kills" in the config to set, try creating the section if it doesn't already exist
     
  3. Offline

    Larsn

    EDIT: NEVERMIND

    I can edit it manually but this doesn't seem to fix it!
     
  4. You should really load files, etc. in the onEnable() and not outside of the method.

    Code:
    private File dispensersFile = null;
    public FileConfigurtaion dData = null;
    
    public void onEnable() {
        // Do code.
        this.dispensersFile = new File(this.getDataFolder(), "Data/DispenserLocations.yml");
        this.dData = YamlConfiguration.loadConfiguration(this.dispensersFile);
    }
    
    Anyway, the reason there is a NullPointerException is because 'plugin' is never set. You set 'instance' but not 'plugin', and why do you even have 2 instance variables? Use one.
     
    Larsn and Xerox262 like this.
  5. Offline

    Larsn

    Still throws the same error
     
  6. Offline

    tytwining

    1) Remember you need to save the config
    2) Are you sure "plugin" or "ddata" isn't null?
     
  7. Offline

    Larsn

    1) It shouldn't throw the error if I am not saving right
    2) Yes
     
  8. ^ Basically what he said.

    The only possible reason (unless you got the line number wrong) that this wouldn't work, is because either 'plugin' or 'ddata' are null. Also, fix your variable names please, follow Oracle programming conventions. I already posted my code with 'dispensersFile' and not 'DispensersFile', etc.

    Post your new code for your main class. Also, print out (before setting the UUID in the config):
    Code:
    System.out.println(plugin != null);
    if (plugin != null) System.out.println(plugin.dData != null);
    
     
    Larsn likes this.
  9. Offline

    tytwining

    I know it shouldn't throw the error if you're not saving, but it's still not going to do anything if you don't save it.
    EDIT: I realize you have a method to save it, but I never see it called?
     
  10. Offline

    Larsn

    Main (open)
    Code:
    package me.Blablballblba.core;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Logger;
    
    import org.bukkit.Bukkit;
    import org.bukkit.configuration.InvalidConfigurationException;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import me.Blablballblba.commands.afCommand;
    import me.Blablballblba.listener.SomeListener;
    
    public class Main extends JavaPlugin {
          
        public final Logger logger = Logger.getLogger("Minecraft");
        public Main plugin;
        public static boolean getDispenserLoc = false;
        public static List<Integer> LocList = new ArrayList<Integer>();
        public static JavaPlugin instance;  
      
      
        /* @Override
        public void onEnable(){
           
            Bukkit.getServer().getPluginManager().registerEvents(new SomeListener(), this);
           getCommand("af").setExecutor(new afCommand());
           this.saveDefaultConfig();
           this.DispensersFile = new File(this.getDataFolder(), "Data/DispenserLocations.yml");
           this.ddata = YamlConfiguration.loadConfiguration(this.DispensersFile);
          
           loadFile(ddata, DispensersFile);
        } */
        
        private File dispensersFile = null;
        public FileConfiguration dData = null;
      
        @Override
        public void onEnable() {
           // Do code.
           this.dispensersFile = new File(this.getDataFolder(), "Data/DispenserLocations.yml");
           this.dData = YamlConfiguration.loadConfiguration(this.dispensersFile);
        }
        
      
        public void loadFile(FileConfiguration ymlConfig, File ymlFile) {
            try {
                    ymlConfig.load(ymlFile);
            } catch (FileNotFoundException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                    e.printStackTrace();
            } catch (InvalidConfigurationException e) {
                    e.printStackTrace();
            }
    }
      
        @Override
        public void onDisable(){
            logger.info("disabled!");
        }
    
        public void saveFile(FileConfiguration ymlConfig, File ymlFile) {
            try {
                    ymlConfig.save(ymlFile);
            } catch (IOException e) {
                    e.printStackTrace();
            }             
        }
      
    }
    
     
  11. By "// do code" I meant, do your previous code (fill it in). It was just an example.

    Anyway, so yeah, you didn't set your plugin instance, therefore it IS null.

    Your actual code should look like:
    Code:
        @Override
        public void onEnable() {
            instance = this;
            plugin = this;
    
            this.getServer().getPluginManager().registerEvents(new SomeListener(), this);
      
            this.getCommand("af").setExecutor(new afCommand());
    
            this.saveDefaultConfig();
            this.dispensersFile = new File(this.getDataFolder(), "Data/DispenserLocations.yml");
            this.dData = YamlConfiguration.loadConfiguration(this.dispensersFile);
        }
    
    But again, why do you have two variables holding the plugin instance? Only have one. There's no need for the local 'plugin' instance if you have a static one ('instance'). However, you should avoid using a static instance of your plugin (not going to go into an argument about this as I use static plugin instances a lot, but I know it's "bad"), just pass in your plugin instance into the constructor of your class.

    E.g.
    Code:
    private Main plugin = null;
    
    public afCommand(Main instance) {
        this.plugin = instance;
    }
    
    Then in your onEnable():
    Code:
    this.getCommand("af").setExecutor(new afCommand(this));
    
    You won't need your 'instance' static variable anymore, as well as not needing your 'plugin' instance in the Main class.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 10, 2016
    Larsn likes this.
  12. Offline

    tytwining

    Nothing is ever added onto this. Meaning it's always that, so always null?
     
  13. Offline

    Larsn

    I have that but it's still throwing the same error
    It does say that these both are null:
    Code:
    System.out.println(plugin != null);
                    if (plugin != null) System.out.println(plugin.dData != null);
    Do I have to import something extra inside afCommand.java?

    It's really late for me sorry if this is just basic knowledge
     
  14. Post your new main class code. I really don't think you're doing what I'm saying xD Does it say "false" or "true", because if it says "true" it means it is NOT null, not that it IS null.

    By the way, I edited my old post, so you can look at that.
     
    Larsn likes this.
  15. Offline

    tytwining

    @KingFaris11 Then stop telling him what to put. :p Simply add "plugin" is null!
     
  16. Offline

    Larsn

    main.java (open)

    Code:
    package me.Blablalblalbl.core;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Logger;
    
    import org.bukkit.Bukkit;
    import org.bukkit.configuration.InvalidConfigurationException;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import me.Blablballba.commands.afCommand;
    import me.Blablballba.listener.SomeListener;
    
    public class Main extends JavaPlugin {
           
        public final Logger logger = Logger.getLogger("Minecraft");
        public Main plugin;
        public static boolean getDispenserLoc = false;
        public static List<Integer> LocList = new ArrayList<Integer>();
        public static JavaPlugin instance;   
       
       
      
        private File dispensersFile = null;
        public FileConfiguration dData = null;
       
        @Override
        public void onEnable() {
            instance = plugin = this;
            this.saveDefaultConfig();
            this.getServer().getPluginManager().registerEvents(new SomeListener(), this);
          
            this.getCommand("af").setExecutor(new afCommand(this));
        }
        
       
        public void loadFile(FileConfiguration ymlConfig, File ymlFile) {
            try {
                    ymlConfig.load(ymlFile);
            } catch (FileNotFoundException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                    e.printStackTrace();
            } catch (InvalidConfigurationException e) {
                    e.printStackTrace();
            }
    }
       
        @Override
        public void onDisable(){
            logger.info("disabled");
        }
    
        public void saveFile(FileConfiguration ymlConfig, File ymlFile) {
            try {
                    ymlConfig.save(ymlFile);
            } catch (IOException e) {
                    e.printStackTrace();
            }             
        }
       
    }


    Man come on, he is trying to help a guy that hasn't got enough sleep (me)
     
  17. It's "late" for him so he probably isn't really thinking straight and understand what I'm trying to say haha xD

    But yeah, 'plugin' is null, and he REALLY should listen to me about not having two instances, one static and one global. He should remove the static one, and even the global one as it's not required in the Main class, only in the other classes referencing the Main class.

    You didn't look at my edited post, I added setting the data File and FileConfiguration.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 10, 2016
    Larsn likes this.
  18. Offline

    tytwining

    Then go to sleep. The quality of your work really plummets when you're tired.
     
    KingFaris11 likes this.
  19. Offline

    Larsn

    Your a boss;
    one last thing, with private main plugin how would I go about saving it as:
    plugin.dData.save(plugin.dispensersFile) wouldn't work

    True but sometimes you just want to finish something, you can't go to sleep then

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 10, 2016
  20. Make a method in the Main class:

    Code:
    public void saveDispensersConfig() {
        try {
            this.dData.save(this.dispensersFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    Then, in your afCommand class, to save the configuration, call that method.

    I'd actually recommend you make 'dData' private and then make another method in the Main class:
    Code:
    public FileConfiguration getDispenersConfig() {
        return this.dData;
    }
    
    And start using that method to get the configuration.
     
    Larsn likes this.
  21. Offline

    Larsn

    Ur a boss.
    Thanks!

    I go to bed now.
     
  22. Haha no problem! Yeahh, I usually stop programming after 1am, I get way too derpy and make the most stupid mistakes, even after making plugins for 3+ years.
     
  23. Offline

    Larsn

    It's 5:30 pm for me but I only slept 3 hours last night. xD
     
    KingFaris11 likes this.
Thread Status:
Not open for further replies.

Share This Page