[Tutorial] How to access the config.yml in an external class! (Constructors)

Discussion in 'Resources' started by Trevor1134, Aug 10, 2013.

?

Did this help you / was this well made?

  1. Yes

    63.6%
  2. No

    31.8%
  3. A little

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

    Trevor1134

    I have created this tutorial to explain how to access the config.yml file from an external class. (Not the main class) Personally, I occasionally forget how to do this, so I would like to help everyone else who doesn't know how to do this.

    I hope I can explain this thoroughly to help you understand constructors fully.

    This also works for any other methods that are accessed in the main class, that cannot be accessed in an external one.

    I understand this is a rather easy tutorial, but this is for more beginners than pros :)


    What a constructor is in terms of Java itself?

    Explanation (open)

    A constructor makes you able to do many things. A constructor runs as soon as it is called in the main code, so as soon as you have:
    Code:
    <Class> <Variable> = new <class>();
    it will run what is in the constructor of that class.



    Now if you have parameters such as a string, this can be used to set a variable.

    Example:

    Code:java
    1. //For this I will use the class name: Apples
    2.  
    3. public class Apples {
    4.  
    5. String name;
    6.  
    7. public Apples(String name) {
    8. this.name = name;
    9.  
    10. }
    11. }

    Now that the constructor has been made, in the MAIN class, you need to call it.
    Code:java
    1. Apples apple = new Apples("Trevor");

    With the above code, what it does it is sets the string 'name' in the class Apples to your parameters. In this case it is 'Trevor.' So now, when ever you access the string 'name' from the class Apples it will return what is in your parameters.

    Example:
    Code:java
    1. public class Main{
    2.  
    3. public static void main(String[] args) {
    4. Apples apple = new Apples("Trevor");
    5.  
    6. System.out.println(apple.name);
    7. }
    8.  
    9. }

    This will print "Trevor" because that is what is in the parameters.


    What you need:
    Items/Programs:
    • A code writing program
    • Basic understanding of java
    What you will create/do:
    At the end of this tutorial, you will know how to:
    • Access the config.yml externally(not main class)
    • create a basic constructor
    First:
    First, you will need to establish the plugin object in the external class. To do so, use the below code.
    Code:
    Code:java
    1. public <Main_Class_Name> plugin;


    Second:
    Second, you will need to create a constructor in the external class. To do that, you need to use the code below.
    Code:
    Code:java
    1. public <class_name>(<Main_Class_Name> plugin){
    2. this.plugin = plugin;
    3. }


    Finally:
    Finally, all you need to do is run the line to access the config. To do so, you will have to use 'plugin' before getConfig().
    Code/Example:
    Code:java
    1. plugin.getConfig()*etc*;


    Now you should be able to access the config from ANY class & you should have a better understanding of Constructors! :)

    Proof?
    is in the pudding! (open)

    [​IMG]


    Thanks for reading, and I hope I helped you!
    Please answer the poll as to if I helped you!
     
  2. Offline

    WazzapDoc

    Very good tutorial

    Support
     
  3. Offline

    zachoooo

    This isn't really a tutorial on accessing the config in an external class, rather accessing variables from other classes.
     
    CeramicTitan likes this.
  4. Offline

    Trevor1134

    zachoooo Good point, but I have found many people asking how to access the config, rather than any other variables.
     
  5. Offline

    zachoooo

    I see
     
  6. Offline

    FozZeW

    If i make methods inside external class then how would i call them corretly with plugin working too, i cant seem to get that working.

    //Methods is my external class
    Methods m = new Methods(plugin);
    and now if i do m.methodName(); then it gives an error

    I think i need to do something on onEnable but not sure
     
  7. Offline

    Garris0n

    I wish I had this tutorial like 5 months ago :p
     
  8. Offline

    Trevor1134

    FozZeW What is the error, and what is the contstructor you have in your external class?
     
  9. Offline

    zachoooo

    I don't want to be THAT GUY, but you need to learn Java. I don't mean this in any negative way, but if you just watched a couple basic tutorials or read a basic book it would sum it up right away.
     
  10. Offline

    FozZeW

    I have same costructor as your tutorial
     
  11. Offline

    tanveergt5

    thanks a lot for this i am a beginner and this helps!
     
  12. Offline

    FozZeW

    Okey i got mine to work now
     
  13. Offline

    Trevor1134

    tanveergt5 Of course :)

    FozZeW Great! Post if you have another issue, I will gladly help.
     
  14. Offline

    Rprrr

    Well.. this is kind of for extreme beginners. ;l Not really useful for people with basic Java knowledge.
     
    zachoooo likes this.
  15. Offline

    Trevor1134

    Rprrr Yes, and you have 8 plugins, but the majority of people here don't...
     
  16. Offline

    Axe2760

    Thank you for this! Hopefully there won't be as many people asking the same questions that can be solved with a constructor now ;)
     
  17. Offline

    Trevor1134

    Axe2760 Thanks! I hope so too :p

    It's my first tutorial, so I just thought I would start with something simple :)
     
  18. Well I can't say anything against the principle of passing in variables via the constructor to use them, BUT when talking about referencing the plugin instance, I don't like it. Not just because I always need to have the plugin reference in the class where I'm instantiating the other class which needs the plugin instance, but also because now my reference is everywhere. A singleton is, in my eyes, a way better solution to this, especially because the JavaPlugin is more or less already a singleton since there will always be only one plugin instance at the time. Because this is already given, the principle of a singleton is way easier to implement and to use, as long as you clean it up properly (one line is most likely enough), then it's all fine.
     
  19. Offline

    zachoooo

    This is the proper way to do it. If you're talking about using a single static instance, that's not good practice
     
  20. zachoooo Not really. It's considered a totally valid design pattern and is widely accepted. That being said, if you use it properly it can in fact be seen as good practice.
     
  21. Offline

    SourceForums

    This tutorial was one of the most helpful tutorials ever. However, it does not work if the external class is implementing CommandExecutor. Help?

    I need answer to this ASAP. Thanks!

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 3, 2016
  22. SourceForums
    What are you talking about? It works just fine if the class implements CommandExecutor. You must've done something wrong. May I see your code?
     
  23. Offline

    SourceForums

    Assist
    Thanks for your quick reply. Here's my code for the main class:
    Code:java
    1. package net.sourceforums.sourcecraft;
    2.  
    3. import java.util.logging.Logger;
    4.  
    5. import net.sourceforums.sourcecraft.SourceCraft;
    6. import net.sourceforums.sourcecraft.Commands.CommandBroadcast;
    7. import net.sourceforums.sourcecraft.Commands.CommandBurn;
    8. import net.sourceforums.sourcecraft.Commands.CommandFly;
    9. import net.sourceforums.sourcecraft.Commands.CommandForce;
    10. import net.sourceforums.sourcecraft.Commands.CommandGetpos;
    11. import net.sourceforums.sourcecraft.Commands.CommandHat;
    12. import net.sourceforums.sourcecraft.Commands.CommandHeal;
    13. import net.sourceforums.sourcecraft.Commands.CommandHub;
    14. import net.sourceforums.sourcecraft.Commands.CommandInvsee;
    15. import net.sourceforums.sourcecraft.Commands.CommandMotd;
    16. import net.sourceforums.sourcecraft.Commands.CommandNick;
    17. import net.sourceforums.sourcecraft.Commands.CommandRules;
    18. import net.sourceforums.sourcecraft.Commands.CommandWarning;
    19. import net.sourceforums.sourcecraft.Listeners.MainPlayerListener;
    20. import net.sourceforums.sourcecraft.Listeners.SuperCraftBrosBrawlPlayerListener;
    21.  
    22. import org.bukkit.plugin.java.JavaPlugin;
    23.  
    24. public class SourceCraft extends JavaPlugin{
    25. public final Logger logger = Logger.getLogger("Minecraft");
    26.  
    27. public static SourceCraft plugin;
    28.  
    29. @Override
    30. public void onEnable(){
    31. new MainPlayerListener(this);
    32. new SuperCraftBrosBrawlPlayerListener(this);
    33. this.saveDefaultConfig();
    34. getCommand("broadcast").setExecutor(new CommandBroadcast());
    35. getCommand("burn").setExecutor(new CommandBurn());
    36. getCommand("fly").setExecutor(new CommandFly());
    37. getCommand("force").setExecutor(new CommandForce());
    38. getCommand("getpos").setExecutor(new CommandGetpos());
    39. getCommand("hat").setExecutor(new CommandHat());
    40. getCommand("heal").setExecutor(new CommandHeal());
    41. getCommand("hub").setExecutor(new CommandHub());
    42. getCommand("invsee").setExecutor(new CommandInvsee());
    43. getCommand("motd").setExecutor(new CommandMotd());
    44. getCommand("nick").setExecutor(new CommandNick());
    45. getCommand("rules").setExecutor(new CommandRules());
    46. getCommand("warning").setExecutor(new CommandWarning());
    47. getCommand("gear").setExecutor(new CommandWarning());
    48. }
    49. }

    Also, here's my code for the class with CommandExecutor:
    Code:java
    1. package net.sourceforums.sourcecraft.Commands;
    2.  
    3. import net.sourceforums.sourcecraft.SourceCraft;
    4.  
    5. import org.bukkit.Bukkit;
    6. import org.bukkit.ChatColor;
    7. import org.bukkit.Location;
    8. import org.bukkit.Material;
    9. import org.bukkit.command.Command;
    10. import org.bukkit.command.CommandExecutor;
    11. import org.bukkit.command.CommandSender;
    12. import org.bukkit.entity.Player;
    13. import org.bukkit.inventory.ItemStack;
    14. import org.bukkit.inventory.PlayerInventory;
    15. import org.bukkit.inventory.meta.BookMeta;
    16. import org.bukkit.inventory.meta.ItemMeta;
    17. import org.bukkit.potion.PotionEffect;
    18. import org.bukkit.scoreboard.DisplaySlot;
    19. import org.bukkit.scoreboard.Objective;
    20. import org.bukkit.scoreboard.Score;
    21. import org.bukkit.scoreboard.Scoreboard;
    22. import org.bukkit.scoreboard.ScoreboardManager;
    23.  
    24. public class CommandHub implements CommandExecutor{
    25. public SourceCraft plugin;
    26.  
    27. public CommandHub(SourceCraft plugin){
    28. this.plugin = plugin;
    29. }
    30.  
    31. public boolean onCommand(CommandSender sender, Command command, String label, String[] args){
    32. Player player = (Player) sender;
    33. PlayerInventory inventory = player.getInventory();
    34. if(args.length == 0){
    35. int creditsValue = plugin.getConfig().getInt(player.getName() + ".economy.credits");
    36. ScoreboardManager boardManager = Bukkit.getScoreboardManager();
    37. Scoreboard stats = boardManager.getNewScoreboard();
    38. Objective objective = stats.registerNewObjective("stats", "dummy");
    39. objective.setDisplaySlot(DisplaySlot.SIDEBAR);
    40. objective.setDisplayName(ChatColor.WHITE + "Stats");
    41. Score credits = objective.getScore(Bukkit.getOfflinePlayer(ChatColor.GOLD + "Credits: "));
    42. credits.setScore(creditsValue);
    43. Score online = objective.getScore(Bukkit.getOfflinePlayer(ChatColor.GREEN + "Online: "));
    44. online.setScore(Bukkit.getOnlinePlayers().length);
    45. player.setScoreboard(stats);
    46. plugin.saveConfig();
    47. ItemStack book = new ItemStack(Material.WRITTEN_BOOK, 1);
    48. ItemStack compass = new ItemStack(Material.COMPASS, 1);
    49. ItemStack clock = new ItemStack(Material.WATCH, 1);
    50. ItemStack emerald = new ItemStack(Material.EMERALD, 1);
    51. ItemStack air = new ItemStack(Material.AIR, 1);
    52. BookMeta bookMeta = (BookMeta) book.getItemMeta();
    53. ItemMeta compassMeta = (ItemMeta) compass.getItemMeta();
    54. ItemMeta clockMeta = (ItemMeta) clock.getItemMeta();
    55. ItemMeta emeraldMeta = (ItemMeta) emerald.getItemMeta();
    56. bookMeta.setTitle(ChatColor.GOLD + "Welcome");
    57. bookMeta.setAuthor(ChatColor.GOLD + "SourceForums");
    58. bookMeta.addPage(ChatColor.GOLD + "WELCOME TO SOURCECRAFT"
    59. + " "
    60. + ChatColor.BLACK + "CONTENT"
    61. + " "
    62. + "1) ABILITIES"
    63. + " "
    64. + "2) RANKS"
    65. + " "
    66. + "3) CONTACT US");
    67. bookMeta.addPage(ChatColor.GOLD + "ABILITIES - DEFAULT"
    68. + ChatColor.BLACK + " "
    69. + "1) /hub"
    70. + " "
    71. + "2) /list"
    72. + " "
    73. + "3) /motd"
    74. + " "
    75. + "4) /rules"
    76. + " "
    77. + "5) /tell"
    78. + " "
    79. + "6) Default Abilities");
    80. bookMeta.addPage(ChatColor.GOLD + "ABILITIES - VIP/EIP"
    81. + ChatColor.BLACK + " "
    82. + "1) /getpos"
    83. + " "
    84. + "2) /me"
    85. + " "
    86. + "3) /nick"
    87. + " "
    88. + "4) /fly"
    89. + " "
    90. + "5-1) 2x Credits (VIP)"
    91. + " "
    92. + "5-2) 3x Credits (EIP)");
    93. bookMeta.addPage(ChatColor.GOLD + "RANKS"
    94. + ChatColor.BLACK + " "
    95. + "1) DEFAULT"
    96. + " "
    97. + "2) VIP"
    98. + " "
    99. + "3) EIP"
    100. + " "
    101. + "4) MOJ/YT/SW"
    102. + " "
    103. + "5) ADMIN"
    104. + " "
    105. + "6) SPECIAL ADMIN");
    106. bookMeta.addPage(ChatColor.GOLD + "CONTACT US"
    107. + ChatColor.BLACK + " "
    108. + "All Contacts on:"
    109. + " "
    110. + "[url]http://sourceforums.net/about[/url]");
    111. compassMeta.setDisplayName(ChatColor.GOLD + "Teleport");
    112. clockMeta.setDisplayName(ChatColor.GOLD + "Visibility");
    113. emeraldMeta.setDisplayName(ChatColor.GOLD + "Store");
    114. book.setItemMeta(bookMeta);
    115. compass.setItemMeta(compassMeta);
    116. clock.setItemMeta(clockMeta);
    117. emerald.setItemMeta(emeraldMeta);
    118. inventory.clear();
    119. for(PotionEffect effect : player.getActivePotionEffects()){
    120. player.removePotionEffect(effect.getType());
    121. }
    122. inventory.setHelmet(air);
    123. inventory.setChestplate(air);
    124. inventory.setLeggings(air);
    125. inventory.setBoots(air);
    126. inventory.addItem(book);
    127. inventory.addItem(compass);
    128. inventory.addItem(clock);
    129. inventory.addItem(emerald);
    130. player.setExp(0);
    131. player.teleport(new Location(Bukkit.getWorld("Hub"), -2, 70, -5));
    132. }
    133. return false;
    134. }
    135. }
    136.  

    The error is: getCommand("hub").setExecutor(new CommandHub());
     
  24. SourceForums
    That's because your CommandHub class constructor has a parameter. Use this instead
    Code:
    getCommand("hub").setExecutor(new CommandHub(this));
     
  25. Offline

    Trevor1134

    Assist Thanks for that, hadn't been on recently.

    SourceForums What Assist said should fix your problem :)
     
  26. Offline

    SourceForums

    Thanks so much guys!
     
  27. Offline

    TrenTech

    Ok been having this issue for quite some time and still I can't figure it out. heres a partial main:

    Code:
    public class EasyKits extends JavaPlugin{
     
        public static EasyKits plugin;
        public final Logger log = Logger.getLogger("Minecraft");
        private EventListener eventlistener;
        private CommandHandler cmdExecutor;
     
        @Override
        public void onEnable(){
         
            new DataSource(this);
    and here's the class that's causing problems:

    Code:
    public class DataSource extends SQLMethods{
     
        private EasyKits plugin;
        public DataSource(EasyKits plugin) {
            this.plugin = plugin;
        }
     
        public static DataSource instance = new DataSource(EasyKits.plugin);
     
        public String getStringConfig(){
            String test = this.plugin.getConfig().getString("Test-String"); <--- NullPointerException!
            return test;
        }
    And a note Test-String does exist in config. Works fine in my EventListener class and my CommandExecutor class. I've made three plugins in the past and this has happened in all the them.. What am I missing?


    NOTE: I know I need to learn Java a little better. Respectfully keep it to yourself's people, I'm just looking for an extra push.
     
  28. Offline

    Trevor1134

    TrenTech Since that isn't registered in the main, like for commandexecutor or listener, I don't believe it will see it as a connection.

    Unless anyone can help me out with this answer, I would say the best choice is to make a variable method in the class to get the plugin... i.e.

    Code:
    private EasyKits getPlugin(){
        return new EasyKits();
    }
     
  29. Offline

    TrenTech

    This appears to have solved my problem

    Code:
        private static EasyKits plugin;
        public DataSource(EasyKits plugin) {
            DataSource.plugin = plugin;
        }
     
  30. Offline

    MordorKing78

    Can u give the full screenshot? plz
     
Thread Status:
Not open for further replies.

Share This Page