Solved NPE when using custom YML outside of Main

Discussion in 'Plugin Development' started by StellarFX, Jan 24, 2020.

  1. Offline

    StellarFX

    Hello everyone!

    I'm trying to create a plugin for my server.
    I'm using a custom YML.
    I noticed that outside of my main class, my commands using this YML are throwing a NPE.
    I guess there's something wrong with my instance...

    Here's my error:
    My error (open)
    [​IMG]


    And here are my classes:
    Main class (open)
    Code:
    public class Main extends JavaPlugin implements Listener {
    
        File usersFilee = new File(getDataFolder(), "users.yml");
        FileConfiguration usersConfig = YamlConfiguration.loadConfiguration(usersFilee);
      
        private static Economy econ = null;
      
        String d = "§7[§6DarkOP§7] §7";
        String separ = "§8----===== {+} =====----";
      
        private boolean setupEconomy() {
            if (getServer().getPluginManager().getPlugin("Vault") == null) {
                return false;
            }
            RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
            if (rsp == null) {
                return false;
            }
            econ = rsp.getProvider();
            return econ != null;
        }
      
        @Override
        public void onEnable() {
            getLogger().info("---------------");
            getLogger().info("Le plugin Entreprise a bien ete active");
            getLogger().info("---------------");
            if(!usersFilee.exists()) {
                saveResource("users.yml", false);
            }
            getLogger().info("---------------");
            getLogger().info("Configuration chargee");
            getLogger().info("---------------");
            getServer().getPluginManager().registerEvents(new YamlHandler(), this);
            getServer().getPluginManager().registerEvents(this, this);
            getCommand("entreprise").setExecutor(new Commands());
          
          
            if(!setupEconomy()) {
                getLogger().severe("---------------");
                getLogger().severe("Plugin désactivé - Vault n'a pas ete trouve !");
                getLogger().severe("---------------");
                getServer().getPluginManager().disablePlugin(this);
              
            }
        }
      
        public File getUsersFile() {
          
            return usersFilee;
        }
      
        public FileConfiguration getUsersConfig() {
          
            return usersConfig;
        }
      
    }
    


    Commands class (open)

    Code:
    package fr.stellarfx.entreprises;
    
    import java.io.File;
    import java.io.IOException;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Material;
    import org.bukkit.OfflinePlayer;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    
    import net.milkbowl.vault.economy.Economy;
    
    public class Commands implements CommandExecutor {
    
        private static Main main;
    
        public static void Listener(Main e) {
            main = e;
        }
    
        private static Economy econ = null;
    
        String d = "§7[§6DarkOP§7] §7";
        String separ = "§8----===== {+} =====----";
    
        boolean delConfirm;
    
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            Player player = (Player) sender;
            if (cmd.getName().equalsIgnoreCase("entreprise")) {
                if (args.length == 0) {
                    player.sendMessage(separ);
                    player.sendMessage("");
                    player.sendMessage("§6/entreprise menu §7: ouvrir le menu d'entreprise");
                    player.sendMessage("§6/entreprise create <nom> §7: créer une entreprise");
                    player.sendMessage("§6/entreprise delete <nom> §7: supprimer une entreprise");
                    player.sendMessage("");
                    player.sendMessage(separ);
                    return true;
                }
                if (args[0].equalsIgnoreCase("menu")) {
                    player.sendMessage("1");
                    if (args.length == 1) {
                        player.sendMessage("Usage: /entreprise menu <nom>");
                        player.sendMessage("2");
                        return false;
                    } else if (args.length == 2) {
                        player.sendMessage("3");
                        if (main.getUsersConfig().getString("users." + player.getName() + ".entreprise.grade." + args[1]).equalsIgnoreCase("Employed") || main.getUsersConfig().getString("users." + player.getName() + ".entreprise.grade." + args[1]).equalsIgnoreCase("Manager")) { //Line 57
                            Inventory menu = Bukkit.getServer().createInventory(player, 27, "§6Menu - Entreprise");
    
                            ItemStack glass = new ItemStack(Material.GRAY_STAINED_GLASS_PANE, 1);
                            ItemMeta glassMeta = glass.getItemMeta();
    
                            glassMeta.setDisplayName(" ");
                            glass.setItemMeta(glassMeta);
    
                            for (int i = 0; i < 27; i++) {
                                menu.setItem(i, glass);
                            }
    
                            ItemStack eC = new ItemStack(Material.BLUE_WOOL);
                            ItemMeta eCmeta = eC.getItemMeta();
    
                            eCmeta.setDisplayName("§9Créer son entreprise");
                            eC.setItemMeta(eCmeta);
    
                            menu.setItem(10, eC);
    
                            player.openInventory(menu);
                        }
                        player.sendMessage("4");
                        return true;
                    }
                } else if (args[0].equalsIgnoreCase("reload")) {
                    YamlConfiguration.loadConfiguration(
                            new File(Bukkit.getPluginManager().getPlugin("Entreprises").getDataFolder(), "users.yml"));
                    return true;
                } else if (args[0].equalsIgnoreCase("register")) {
                    if(args.length == 2) {
                        main.getUsersConfig().set("users." + player.getName() + ".entreprise." + args[1] + ".grade", "Unemployed");
                        try {
                            main.getUsersConfig().save(main.getUsersFile());
                            player.sendMessage(d + "Vous avez bien été enregistré");
                        } catch (IOException e) {
                            e.printStackTrace();
                            player.sendMessage(d + "Une erreur est survenue lors de l'enregistrement");
                        }
                        return true;
                    } else {
                        player.sendMessage(d + "Usage: /entreprise register <nom>");
                        return false;
                    }
                } else if (args[0].equalsIgnoreCase("create")) {
                    if (args.length == 1) {
                        player.sendMessage(d + "Usage: /entreprise create <nom>");
                        return false;
                    } else if (args.length == 2) {
                        if (econ.getBalance((OfflinePlayer) player) >= 25000) {
                            main.getUsersConfig().set("users." + player.getName() + ".entreprise." + args[1] + ".nom", args[1]);
                            main.getUsersConfig().set("users." + player.getName() + ".entreprise." + args[1] + ".grade", "PDG");
                            econ.withdrawPlayer((OfflinePlayer) player, 25000);
                            player.sendMessage(d + "Vous avez créé une entreprise !");
                            return true;
                        } else {
                            player.sendMessage(d + "Vous n'avez pas assez d'argent!");
                            player.sendMessage(d + "Argent requis: " + (25000 - econ.getBalance((OfflinePlayer) player)));
                            return false;
                        }
                    }
                } else if (args[0].equalsIgnoreCase("delete")) {
                    if (args[1].isEmpty()) {
                        player.sendMessage(d + "Usage: /entreprise delete <nom>");
                        return false;
                    } else {
                        if (main.getUsersConfig().getString("users." + player.getName() + ".entreprise.nom")
                                .contains(args[1])) {
                            if (main.getUsersConfig().getString("users." + player.getName() + ".entreprise.grade." + args[1])
                                    .equalsIgnoreCase("PDG")) {
                            }
                            if (delConfirm = false) {
                                player.sendMessage(separ);
                                player.sendMessage(
                                        "&cÊtes vous sûr de vouloir supprimer votre entreprise ? Cette action est irréversible !");
                                player.sendMessage(
                                        "&cTapez '&6/entreprise delete <nom> confirm' &cpour supprimer votre entreprise !");
                                player.sendMessage(separ);
                                delConfirm = true;
                                return false;
                            } else if (delConfirm = true) {
                                main.getUsersConfig().set("users." + player.getName() + ".entreprise.nom." + args[1], "");
                                main.getUsersConfig().set("users." + player.getName() + ".entreprise.grade." + args[1],
                                        "Unemployed");
                                main.getUsersConfig().set("users." + player.getName() + ".entreprise.nom." + args[1], null);
                                player.sendMessage(d + "Vous avez supprimé votre entreprise !");
                                delConfirm = false;
                                return true;
                            } else {
                                player.sendMessage(d + "§cVous n'êtes pas le PDG de l'entreprise !");
                                return false;
                            }
                        } else {
                            player.sendMessage(d + "Votre entreprise n'existe pas !");
                            player.sendMessage("§8§oVous pensez que c'est une erreur ? Contactez un administrateur.");
                            return false;
                        }
                    }
                }
            }
            return false;
        }
    }
    


    Thanks in advance!

    EDIT : It's doing this whenever I try to use custom YMLs.
     
  2. Offline

    timtower Moderator Moderator

  3. Offline

    DerDonut

    But that shouldn't throw the npe in l 57

    @StellarFX Put the declaration of usersFile and usersConfig inside the onEnable
     
  4. Offline

    timtower Moderator Moderator

    @DerDonut I don't even know what line 57 is
     
  5. Offline

    StellarFX

    @timtower Okay thank you I modified that, but that doesn't solve my inital problem.

    EDIT : I put a "// Line 57". It's a looong if
    RE-EDIT : It's in the "menu" arg

    @DerDonut That is to say? I'm using "getUsersFile()" and "getUsersConfig()" methods to pass variables between classes, if I put the declaration in my onEnable(), won't it destroy my methods ?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jan 24, 2020
  6. Offline

    DerDonut

    @StellarFX sorry I meant the initialization not the declaration.
     
  7. Offline

    StellarFX

    @DerDonut Okay I initialized my "usersFile" and "usersConfig" inside my onEnable(), but it didn't change anything.
    I repeat that if I put my commands in my "Main" class, everything works fine.
     
  8. Offline

    DerDonut

    You never call
    Code:
    public static void Listener(Main e) {
       main = e;
    }
    thats why your Main instance is null.
    Remove that piece of code and create a proper constructor for your Commands class
     
  9. Offline

    StellarFX

    @DerDonut Okay thanks for your help. I fixed it, I don't know how but I did. Thank you!
     

Share This Page