Solved Access main configuration file within event

Discussion in 'Spigot Plugin Development' started by Bjorno43, Jun 23, 2019.

  1. Hey everyone :)

    I'm working on the economy part of my plugin and I'm trying to implement giving players a starting balance. As I obviously don't want to force users to use the integrated economy, I only wish to do this if integrated economy is enabled in the main configuration file.

    This is what I've tried to accomplish this (removed everything irrelevant):

    Main.java
    Code (Java):
    import org.bukkit.plugin.java.JavaPlugin;

    public class Main extends JavaPlugin {
        private FileConfiguration conf = getConfig();

        public FileConfiguration getMainConfig() {
           return this.conf;
        }
    }
    Then inside my player joined event I'm trying this:
    Code (Java):
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;

    import com.bjorno43.iceshops.Main;

    public class PlayerJoined implements Listener {
       
        @EventHandler
        public void onPlayerJoin(PlayerJoinEvent event) {
            if(!event.getPlayer().hasPlayedBefore()) {
                if (getMainConfig().getBoolean("enable-economy")) {
                   
                }
            }
        }
    }
    But I keep running in either of these 2 exceptions:
    Perhaps I'm using the wrong approach here or am I simply making some small mistake here? Any help would be much appreciated.
     
  2. Hello,

    You must pass your class into the new listener class:
    In your main class (which extends JavaPlugin), register your event like this:
    Code (Java):
    getServer().getPluginManager().registerEvents(new PlayerJoined(this), this);
    And, in your listener class (PlayerJoined), create a specific constructor:
    Code (Java):
    private final Main main;
    public PlayerJoined(Main main){
        this.main = main;
    }
    So, in your event, you'll can call main.getMainConfig().
     
    • Like Like x 1
  3. Yup, that fixed the issue. Thanks a lot! :D