How to check if a configuration section contains at least one key?

Discussion in 'Plugin Development' started by Maxx_Qc, Jun 1, 2015.

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

    Maxx_Qc

    Hi, I want to make a list from my configuration section.

    Code:
    if (args[0].equalsIgnoreCase("list")) {
                            if (args.length == 1) {
                                FileConfiguration config = null;
                                File file = new File(Main.getPlugin().getDataFolder()+File.separator+"donjons.yml");
                                config = YamlConfiguration.loadConfiguration(file);
                                StringBuilder sb = new StringBuilder();
                               String prefix = "";
                               for(String s : config.getConfigurationSection("donjons").getKeys(false)) {
                                   sb.append(prefix);
                                   prefix = ", ";
                                   sb.append(s);
                               }
                               sender.sendMessage(colorize("&6&l> &7Donjons: " + sb.toString()));
                            } else {
                                sender.sendMessage(colorize("&6&l> &7Usage: /dj list"));
                            }
                        }
    
    The problem is, when there's no key for this configuration section, it returns : "Donjons: " but I want it to return "There's no donjons yet!".
    Thank you in advance, I speak french, so Donjon = Dungeon

    Got it with try and catch! (NullPointerException)

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 12, 2016
  2. That's a terrible way to do it, never purposely try getting an error, it's best to handle it. A better way would be:
    Code:
    Set<String> donjons = config.contains("donjons") ? config.getConfigurationSection("donjons").getKeys(false) : null; // Check if the config contains "donjons", if so, get all the keys, if not, return null.
    if (donjons != null && !donjons.isEmpty()) { // Check if the donjons Set isn't empty.
        // Do for loop.
    } else {
        sb.append("There's no donjons yet!");
    }
    
    By the way, you should really instead have a global variable for the configuration, instead of loading it each time someone types the command.
     
Thread Status:
Not open for further replies.

Share This Page