Solved Help pls :( Calling method from another class inside @EventHandler

Discussion in 'Plugin Development' started by TH3_GR13F, Sep 26, 2021.

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

    TH3_GR13F

    Hello so i'm more than likely going to get roasted here w/ the classic, learn java b4 you learn bukkit and all that but I am but a lowly server-host attempting to self-teach myself how to code w/ bukkit via just forcing out a plugin whilst watching tutorials and reading about how to code so please don't be too brutal to me. Anyways, here's what i've got. Basically I am trying to re-create, from scratch, a working WatchBlock. In the interest of learning, and trying to keep things organized i'm splitting alot of things into different classes, I would like to continue doing this if possible.

    The code in question is an @EventHandler that looks for a playerlogin event and on seeing someone log in, it runs the createPlayer() method out of FriendsHandler.java class. However, when a player joins i'm presented w/ this error.

    Code:
    [23:52:48] [User Authenticator #1/INFO]: UUID of player n0_grief is fb8ceebb-d091-485e-bf95-ec27c6e03797
    [23:52:48] [Server thread/ERROR]: Could not pass event PlayerJoinEvent to WatchBlock v2.0
    java.lang.NullPointerException: Cannot invoke "com.n0grief.WatchBlock.SQL.FriendsHandler.createPlayer(org.bukkit.entity.Player)" because "this.friendshandler" is null
        at com.n0grief.WatchBlock.EventHandler.Join.onJoin(Join.java:14) ~[WatchBlock A-6.0.jar:?]
        at com.destroystokyo.paper.event.executor.asm.generated.GeneratedEventExecutor3.execute(Unknown Source) ~[?:?]
        at org.bukkit.plugin.EventExecutor.lambda$create$1(EventExecutor.java:69) ~[patched_1.17.1.jar:git-Paper-266]
        at co.aikar.timings.TimedEventExecutor.execute(TimedEventExecutor.java:80) ~[patched_1.17.1.jar:git-Paper-266]
        at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.java:70) ~[patched_1.17.1.jar:git-Paper-266]
        at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.java:624) ~[patched_1.17.1.jar:git-Paper-266]
        at net.minecraft.server.players.PlayerList.postChunkLoadJoin(PlayerList.java:360) ~[patched_1.17.1.jar:git-Paper-266]
        at net.minecraft.server.players.PlayerList.lambda$placeNewPlayer$1(PlayerList.java:302) ~[patched_1.17.1.jar:git-Paper-266]
        at net.minecraft.server.network.PlayerConnection.tick(PlayerConnection.java:307) ~[patched_1.17.1.jar:git-Paper-266]
        at net.minecraft.network.NetworkManager.a(NetworkManager.java:555) ~[patched_1.17.1.jar:git-Paper-266]
        at net.minecraft.server.network.ServerConnection.c(ServerConnection.java:201) ~[patched_1.17.1.jar:git-Paper-266]
        at net.minecraft.server.MinecraftServer.b(MinecraftServer.java:1648) ~[patched_1.17.1.jar:git-Paper-266]
        at net.minecraft.server.dedicated.DedicatedServer.b(DedicatedServer.java:479) ~[patched_1.17.1.jar:git-Paper-266]
        at net.minecraft.server.MinecraftServer.a(MinecraftServer.java:1475) ~[patched_1.17.1.jar:git-Paper-266]
        at net.minecraft.server.MinecraftServer.x(MinecraftServer.java:1274) ~[patched_1.17.1.jar:git-Paper-266]
        at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:319) ~[patched_1.17.1.jar:git-Paper-266]
        at java.lang.Thread.run(Thread.java:833) [?:?]
    [23:52:48] [Server thread/INFO]: n0_grief joined the game
    [23:52:48] [Server thread/INFO]: n0_grief[/127.0.0.1:49222] logged in with entity id 184 at ([world]97.51333801736334, 86.86813563770782, 235.72056333995056)
    

    My assumption that the problem has possibly something to do w/ either the argument 'player' that I am trying to use in the code for the createPlayer() method?? But tbh i'm not sure and the only person i know that knows anything about java hasn't been able to help either.

    Here is the code for Join.java which is the class that looks for PlayerJoinEvent and attempts to call the createPlayer() method when people join.

    Code:
    package com.n0grief.WatchBlock.EventHandler;
    
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;
    import com.n0grief.WatchBlock.SQL.FriendsHandler;
    
    public class Join implements Listener {
        public FriendsHandler friendshandler;
        @EventHandler
        public void onJoin(PlayerJoinEvent event) {
            Player player = event.getPlayer();
            friendshandler.createPlayer(player);
        }
       
    }
    
    Here is the suspected crappy class that the createPlayer() method is called from in Join.java.

    Code:
    package com.n0grief.WatchBlock.SQL;
    
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.UUID;
    
    import org.bukkit.Bukkit;
    import org.bukkit.entity.Player;
    
    import com.n0grief.WatchBlock.Main;
    
    public class FriendsHandler {
        private Main plugin;
        public FriendsHandler(Main plugin) {
            this.plugin = plugin;
        }
        public void createPlayer(Player player) {
            try {
                UUID uuid = player.getUniqueId();
                if(!exists(uuid)) {
                    PreparedStatement ps2 = plugin.SQL.getConnection().prepareStatement("INSERT IGNORE INFO wb_friends" + "(NAME,UUID) VALUES (?,?)");
                    ps2.setString(1, player.getName());
                    ps2.setString(2, uuid.toString());
                    ps2.executeUpdate();
                    Bukkit.getLogger().info("[WATCHBLOCK] NEW PLAYER: " + player + " has been added to the wb_friends table.");
                    return;
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //This method checks to see if a player already exists in the database.
        public boolean exists(UUID uuid) {
            try {
                PreparedStatement ps = plugin.SQL.getConnection().prepareStatement("SELECT * FROM wb_friends WHERE UUID=?");
                ps.setString(1, uuid.toString());
               
                ResultSet results = ps.executeQuery();
                if(results.next()) {
                    return true;
                }
                return false;
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
            return false;
        }
    }
    
    As i said before, i am completely new at this and am trying to learn on my own but this has me stumped, i feel like this is a stupid simple problem but i haven't been able to find anything to help myself which is why i have finally come here. I've been troubleshooting in a bunch of different ways for the last 3 nights attempting to figure out what is wrong but haven't had any luck, someone i know that's familiar w/ javascript but not w/ bukkit suggested it's possible the @EventHandler is putting my method out of scope which is why it's returning null but i have (i think) eliminated this possibility as i have been able to plug in another method from another class inside the same @EventHandler in Join.java and have had it run perfectly fine. Any help here would be much appreciated. Thank you in advance :)

    I'm not sure if Main class will be needed but going to post it here just in case
    Code:
    package com.n0grief.WatchBlock;
    
    import java.sql.SQLException;
    import org.bukkit.Bukkit;
    import org.bukkit.event.Listener;
    import org.bukkit.plugin.java.JavaPlugin;
    import com.n0grief.WatchBlock.EventHandler.BlockTracker;
    import com.n0grief.WatchBlock.EventHandler.Join;
    import com.n0grief.WatchBlock.Methods.AddFriendCommand;
    import com.n0grief.WatchBlock.Methods.FlatLogCreator;
    import com.n0grief.WatchBlock.Methods.FriendsCreator;
    import com.n0grief.WatchBlock.SQL.MYSQL;
    import com.n0grief.WatchBlock.SQL.TableCreator;
    
    public class Main extends JavaPlugin implements Listener {
       
        public MYSQL SQL;
        public TableCreator tablecreator;
        @Override
        public void onEnable() {
            //Load Config.yml into RAM / method for handling configuration queries
            getConfig().options().copyDefaults();
            saveDefaultConfig();
            //Find or create FlatLog file
            FlatLogCreator.setupblocksflatfile();
            //Find or create Friends-List file
            FriendsCreator.setupfriendslist();
            //SQL CONNECTION HANDLER
            this.tablecreator = new TableCreator(this);
            this.SQL = new MYSQL();
            try {
                SQL.connect();
            } catch (ClassNotFoundException | SQLException e) {
                //e.printStackTrace();
                Bukkit.getLogger().info("[WATCHBLOCK] DATABASE DID NOT CONNECT SUCCESSFULLY");
                Bukkit.getLogger().info("[WATCHBLOCK] DID YOU TYPE YOUR LOGIN DETAILS IN CORRECTLY IN CONFIG?");
            }
            if(SQL.isConnected()) {
                Bukkit.getLogger().info("[WATCHBLOCK] MYSQL DATABASE HAS SUCCESSFULLY BEEN CONNECTED!");
                tablecreator.createFriendsTable();
                Bukkit.getLogger().info("[WATCHBLOCK] FRIENDS TABLE CREATED/LOADED.");
                tablecreator.createBlocksTable();
                Bukkit.getLogger().info("[WATCHBLOCK] BLOCKS TABLE CREATED/LOADED.");
            //END OF SQL CONNECTION HANDLER
            }
            getServer().getPluginManager().registerEvents(new BlockTracker(), this);
            getServer().getPluginManager().registerEvents(new Join(), this);
            new AddFriendCommand(this);
        }
       
        @Override
        public void onDisable() {
            SQL.disconnect();
        }
    
    }
    
    
    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Sep 27, 2021
  2. Online

    timtower Administrator Administrator Moderator

    @TH3_GR13F Never set the friendshandler in the Join class
     
  3. Offline

    TH3_GR13F

    I'm sure this is a super stupid question so sorry for asking it but what exactly are you meaning by setting friendshandler in Join class? I did a little searching and didn't find any obvious answers on google, as I said i'm like super new to all this and kinda suprised i got this far.
     
  4. Online

    timtower Administrator Administrator Moderator

    Code:
    public FriendsHandler friendshandler;
    This line never gets a value in your code.
     
  5. Offline

    TH3_GR13F

    lol i feel embarassed even asking but how exactly is this accomplished? Not asking to be spoonfed but i'm so not familiar w/ the language lingo & am trying to understand what i'm doing as i'm doing it if it makes sense, if you could explain a little bit i would be super appreciative. Is this done with something along the lines of
    Code:
     this.friendshandler = new FriendsHandler(this); 
    ? or am i completely off base, don't think this is something i have had to do yet.
     
  6. Online

    timtower Administrator Administrator Moderator

    @TH3_GR13F Making a new one would be bad, add a constructor.
     
  7. Offline

    TH3_GR13F

    solved by changing Main.java to
    Code:
    package com.n0grief.WatchBlock;
    
    import java.sql.SQLException;
    
    import org.bukkit.Bukkit;
    import org.bukkit.event.Listener;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import com.n0grief.WatchBlock.EventHandler.BlockTracker;
    import com.n0grief.WatchBlock.EventHandler.Join;
    import com.n0grief.WatchBlock.Methods.AddFriendCommand;
    import com.n0grief.WatchBlock.Methods.FlatLogCreator;
    import com.n0grief.WatchBlock.Methods.FriendsCreator;
    import com.n0grief.WatchBlock.SQL.FriendsHandler;
    import com.n0grief.WatchBlock.SQL.MYSQL;
    import com.n0grief.WatchBlock.SQL.TableCreator;
    
    import net.md_5.bungee.api.ChatColor;
    
    public class Main extends JavaPlugin implements Listener {
      
        public MYSQL SQL;
        public TableCreator tablecreator;
        public FriendsHandler friendshandler;
        public Join join;
        @Override
        public void onEnable() {
            //Load Config.yml into RAM / method for handling configuration queries
            getConfig().options().copyDefaults();
            saveDefaultConfig();
            //Find or create FlatLog file
            FlatLogCreator.setupblocksflatfile();
            //Find or create Friends-List file
            FriendsCreator.setupfriendslist();
            //SQL CONNECTION HANDLER
            this.tablecreator = new TableCreator(this);
            this.friendshandler = new FriendsHandler(this);
            this.SQL = new MYSQL();
            try {
                SQL.connect();
            } catch (ClassNotFoundException | SQLException e) {
                //e.printStackTrace();
                Bukkit.getLogger().info(ChatColor.RED + "[WATCHBLOCK] DATABASE DID NOT CONNECT SUCCESSFULLY");
                Bukkit.getLogger().info(ChatColor.RED + "[WATCHBLOCK] DID YOU TYPE YOUR LOGIN DETAILS IN CORRECTLY IN CONFIG?");
            }
            if(SQL.isConnected()) {
                Bukkit.getLogger().info(ChatColor.GREEN + "[WATCHBLOCK] MYSQL DATABASE HAS SUCCESSFULLY BEEN CONNECTED!");
                tablecreator.createFriendsTable();
                Bukkit.getLogger().info(ChatColor.GREEN + "[WATCHBLOCK] FRIENDS TABLE CREATED/LOADED.");
                tablecreator.createBlocksTable();
                Bukkit.getLogger().info(ChatColor.GREEN + "[WATCHBLOCK] BLOCKS TABLE CREATED/LOADED.");
            //END OF SQL CONNECTION HANDLER
            }
            getServer().getPluginManager().registerEvents(new BlockTracker(), this);
            getServer().getPluginManager().registerEvents(new Join(friendshandler), this);
            new AddFriendCommand(this);
        }
      
        @Override
        public void onDisable() {
            SQL.disconnect();
        }
    
    }
    


    and Join.java to
    Code:
    package com.n0grief.WatchBlock.EventHandler;
    
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;
    import com.n0grief.WatchBlock.SQL.FriendsHandler;
    
    public class Join implements Listener {
        private final FriendsHandler friendshandler;
        public Join(FriendsHandler friendshandler) {
            this.friendshandler = friendshandler;
        }
        @EventHandler
        public void onJoin(PlayerJoinEvent event) {
            Player player = event.getPlayer();
            friendshandler.createPlayer(player);
        }
      
    }
    
    
    Thank you for the help :)
     
Thread Status:
Not open for further replies.

Share This Page