Solved Problem with load HashMap

Discussion in 'Spigot Plugin Development' started by Ziomkeee, Aug 8, 2018.

  1. Hey. I do not know why, but when a player enters the server he / she correctly downloads the data from the config to the hashmap, but when he enters check commands, he shows that the hashmap is empty. String, Player, UUID always = empty

    Code (Java):
        @EventHandler
        public void loadHashMap(PlayerJoinEvent e) {
            Player p = e.getPlayer();
            if(cfg.getData().isSet("data." + p.getName() + ".fly")) {
                flyTime.put(p.getName(), cfg.getData().getInt("data." + p.getName() + ".fly"));
            } else {
                flyTime.put(p.getName(), 0);
            }
            System.out.println(flyTime.get(p.getName())); //DEBUG
        }
    Check command: (args)
    Code (Java):
                if(args.length == 1) {
                    if(args[0].equalsIgnoreCase("info")) {
                        if(flyTime.get(p.getName()) != null) {
                            if(flyTime.get(p.getName()) > 0) {
                                p.sendMessage("§7Fly §6" + flyTime.get(p.getName())  + " min§7!");
                            } else {
                                p.sendMessage("§cnope!");
                            }
                        } else {
                            p.sendMessage("§cnope!!");
                        }
                    }
                }
     
  2. Full code is needed for us to understand what's happening
     
  3. Are you using different instances for the CommandExecutor and the Listener? You should use the same instance for both.
     
  4. Code (Java):


    import org.bukkit.Bukkit;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.event.player.PlayerQuitEvent;
    import pl.marketdesign.cashcore.classicmc;

    import java.util.HashMap;
    import java.util.UUID;

    import static pl.marketdesign.cashcore.classicmc.cfg;


    public class flyCmd implements CommandExecutor, Listener {

        private classicmc plugin = classicmc.getPlugin(classicmc.class);

        public int taskID;
        public HashMap<String, Integer> flyTime = new HashMap<>();
        public HashMap<UUID, Boolean> flyStatus = new HashMap<>();
        public HashMap<UUID, Integer> flyTask = new HashMap<>();

        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String s, String[] args) {
            if(cmd.getName().equalsIgnoreCase("fly")) {
                Player p = (Player) sender;
                if(args.length == 0) {
                    if(flyStatus.get(p.getUniqueId()) == null || flyStatus.get(p.getUniqueId()) == false) {
                        if(flyTime.get(p.getName()) != null && flyTime.get(p.getName()) > 0) {
                            flyStatus.put(p.getUniqueId(), true);
                            p.setAllowFlight(true);
                            startFly(p);
                            p.sendMessage("§7fly §aoff§7!");
                        } else {
                            p.sendMessage("§cnope!");
                        }
                    } else {
                        flyStatus.put(p.getUniqueId(), false);
                        p.setAllowFlight(false);
                        Bukkit.getScheduler().cancelTask(flyTask.get(p.getUniqueId()));
                        p.sendMessage("§7fly §con§7!");
                    }
                }
                if(args.length == 1) {
                    if(args[0].equalsIgnoreCase("info")) {
                        if(flyTime.get(p.getName()) != null) {
                            if(flyTime.get(p.getName()) > 0) {
                                p.sendMessage("§7Fly §6" + flyTime.get(p.getName())  + " min§7!");
                            } else {
                                p.sendMessage("§cnope!");
                            }
                        } else {
                            p.sendMessage("§cnope!!");
                        }
                    }
                }
                if(args.length == 3) {
                    if(p.hasPermission("cashcore.repair.admin")) {
                        if(args[0].equalsIgnoreCase("give")) {
                            String nick = args[1];
                            int amount = Integer.parseInt(args[2]);
                            if(!nick.isEmpty()) {
                                Player target = Bukkit.getPlayer(nick);
                                if(flyTime.get(p.getName()) == null) {
                                    flyTime.put(target.getName(), amount);
                                } else {
                                    flyTime.put(target.getName(), flyTime.get(target.getName())+amount);
                                }
                                target.sendMessage("§7FLY §6" + flyTime.get(target.getName()) + " min§7!");
                            } else {
                                p.sendMessage("§c/fly give NICK AMOUNT");
                            }
                        }
                    } else {
                        p.sendMessage("§cUżyj: /fly");
                    }
                }
            }
            return false;
        }

        public void startFly(Player p ) {
            taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
                @Override
                public void run() {
                    flyTime.put(p.getName(), flyTime.get(p.getName())-1);
                    p.sendMessage(String.valueOf(flyTime.get(p.getName())));
                    //////////
                    if(flyTime.get(p.getName()) == 0 || flyTime.get(p.getName()) == -1) {
                        Bukkit.getScheduler().cancelTask(flyTask.get(p.getUniqueId()));
                        flyStatus.put(p.getUniqueId(), false);
                        p.setAllowFlight(false);
                        p.sendMessage("§cEND!");
                        return;
                    }
                }
            }, 1200, 1200);
            flyTask.put(p.getUniqueId(), taskID);
        }


        @EventHandler
        public void loadHashMap(PlayerJoinEvent e) {
            Player p = e.getPlayer();
            if(cfg.getData().isSet("data." + p.getName() + ".fly")) {
                flyTime.put(p.getName(), cfg.getData().getInt("data." + p.getName() + ".fly"));
            } else {
                flyTime.put(p.getName(), 0);
            }
            System.out.println(flyTime.get(p.getName())); //DEBUG
        }


        @EventHandler
        public void saveHashMap(PlayerQuitEvent e) {
            Player p = e.getPlayer();
            System.out.println(flyTime.get(p.getName()));
            if(flyTime.get(p.getName()) != null) {
                cfg.getData().set("data." +  p.getName() + ".fly", flyTime.get(p.getName()));
                cfg.dataSave();
            }
            if(flyStatus.get(p.getUniqueId()) != null && (flyStatus.get(p.getUniqueId()) == true)) {
                flyStatus.put(p.getUniqueId(), false);
                Bukkit.getScheduler().cancelTask(flyTask.get(p.getUniqueId()));
                p.setAllowFlight(false);
            }
        }
    }
     
     
  5. Yes you're likely using two instances. Use one to register as listener and as command executor.

    Moreover,
    • Just pass the Plugin instance directly to the class via its constructor. Avoid static where possible, unless it concerns constants (static final fields). Static methods only operating on input and output are generally ok (but be wary of them)
    • Fields should be private, not public.
    • Liskov Substitution Principle, you should program against abstractions (e.g. Map) rather than implementations (e.g. HashMap)
    • Prefer early returns over nesting if statements, to reduce indentation.
      Code (Java):
      if (!statement) {
          return;
      }
      // Rather than
      if (statement) {
          // Rest of code
      }
    • Avoid the old BukkitScheduler methods which return ints. Use the runTask methods which return BukkitTasks instead (you can call BukkitTask::cancel on them to cancel the task)
    • Store the result of method calls I'd you're going to use it later. I.e. map.get(key) should be stored in a variable and then null checked and used.
    • Use a delayed task and Set rather than a repeating task with a Map. Less complexity, uses less resources as well. Only reason to use a Map is if you want to use the number.
    • Handle errors. parseInt could throw a NumberFormatException if the user doesn't provide you with a number.
    • Follow code standards. Class names should use PascalCase.
     
    • Like Like x 2