0

Okay, so I'm trying to make a toggleable feature, whether they have it enabled/disabled is stored in the 'data.yml'. The issue I have with this is that the file does get updated (Asin, it does change from true to false and vice versa) but it doesn't actually apply the changes in-game.

Method for reloading the file:

public static void reloadConfig(File file, FileConfiguration conf) {
    try {
        conf.save(file);
    } catch (Exception e) {
    }
    conf = YamlConfiguration.loadConfiguration(file);
}

Toggle command:

if (args[0].equalsIgnoreCase("toggle")) {
    File file = new File("plugins/StatTrack", "data.yml");
    if (file.exists()) {
        FileConfiguration conf = YamlConfiguration.loadConfiguration(file);
        if (conf.getBoolean("Users." + player.getName() + ".OreTracker") == true) {
            conf.set("Users." + player.getName() + ".OreTracker", false);
            try {
                Main.reloadConfig(file, conf);
                Main.message(player, "&cDisabled&f the Ore&8-&fTracker");
                return true;
            } catch (Exception e) {
                Main.message(player, "&cSome fatal error occored");
                return true;
            }
        } else if (conf.getBoolean("Users." + player.getName() + ".OreTracker") == false) {
            conf.set("Users." + player.getName() + ".OreTracker", true);
            try {
                Main.reloadConfig(file, conf);
                Main.message(player, "&aEnabled&f the Ore&8-&fTracker");
                return true;
            } catch (Exception e) {
                Main.message(player, "&cSome fatal error occored");
                return true;
            }
        }
    }
}

If you need any more code or have any questions I'll happily supply the code/answer. Thanks in advance.

Askingg
  • 107
  • 1
  • 2
  • 11

1 Answers1

0

The problem is that the plugin is saving the config in the reload method. I also wouldn't recommend using a static method in this case unless the class of the method is a Singleton.

So let's create a new class being a Singleton. The Singleton pattern describes a class which has only one instance accessible through static methods.

public class PluginConfig {

    private static PluginConfig instance; // Static (global) reference to the instance

    File confFile;
    YamlConfiguration conf;

    public PluginConfig(File confFile) {
        this.confFile = confFile;
        loadConfig();
    }

    public static YamlConfiguration getConfig() {
        return instance.conf;
    }

    public static void loadConfig() {
        instance.conf = YamlConfiguration.loadConfiguration(confFile);
    }

    // Extra method for another implementation, if potentially needed in the future
    public static void reloadConfig() {
        loadConfig();
    }

}

Using that class you can access the config from everywhere with PluginConfig.getConfig()

Glowdragon
  • 51
  • 4