Solved NullPointerException error when trying to create list of custom object

Discussion in 'Plugin Development' started by KingOfMars4, Nov 7, 2020.

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

    KingOfMars4

    Hey, so as the name says im trying to create a list of a custom object yet it gives this error:

    Basically what I'm trying to do is a RTS plugin with spigot 1.8.8 with 3 custom objects:
    - Lobbys
    - Countries
    - Territories

    Each lobby has his own countries, each countries have their own territories.

    I succefully created a list of countries by lobby, which means that every lobby has his own Countries and that part is working.
    Im trying to do the same scheme with territories but i get this error:
    https://pastebin.com/BG8crqKr

    If you have any idea or solution for this please let me know.

    Some classes:
    Lobby:
    Code:
    package me.kingofmars4.hoc.handlers.lobbies;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.UUID;
    
    import org.bukkit.Location;
    
    import me.kingofmars4.hoc.handlers.countries.Countrie;
    import me.kingofmars4.hoc.handlers.territories.Territorie;
    
    public class Lobby {
      
        private final int id;
        private final Location spawn;
        private final List<UUID> players = new ArrayList<UUID>();
        private final List<Countrie> countries = new ArrayList<Countrie>();
        private final List<Territorie> territories = new ArrayList<Territorie>();
      
        public Lobby(Location spawn, int id) {
            this.spawn = spawn;
            this.id = id;
        }
      
        public int getId() {
            return this.id;
        }
      
        public List<UUID> getPlayers() {
            return this.players;
        }
      
        public Location getSpawn() {
            return this.spawn;
        }
      
        public List<Countrie> getCountries() {
            return this.countries;
        }
      
        public List<Territorie> getTerritories() {
            return this.territories;
        }
    
    }
    
    LobbyManager
    Code:
    package me.kingofmars4.hoc.handlers.lobbies;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.UUID;
    import org.bukkit.Bukkit;
    import org.bukkit.Location;
    import org.bukkit.Material;
    import org.bukkit.entity.Player;
    import org.bukkit.inventory.ItemStack;
    import me.kingofmars4.hoc.files.FileLobbys;
    import me.kingofmars4.hoc.handlers.countries.Countrie;
    import me.kingofmars4.hoc.handlers.countries.CountrieManager;
    import me.kingofmars4.hoc.handlers.territories.Territorie;
    import me.kingofmars4.hoc.utils.U;
    
    public class LobbyManager {
      
        private static LobbyManager lm;
      
        private final Map<UUID, Location> locs = new HashMap<UUID, Location>();
        private final Map<UUID, ItemStack[]> inv = new HashMap<UUID, ItemStack[]>();
        private final Map<UUID, ItemStack[]> armor = new HashMap<UUID, ItemStack[]>();
      
        private final List<Lobby> Lobbys = new ArrayList<Lobby>();
      
        public static int LobbySize = 0;
      
        private LobbyManager() {}
      
        public List<Lobby> getLobbys() {
            return Lobbys;
        }
      
        public static LobbyManager get() {
            if (lm == null)
                lm = new LobbyManager();
            return lm;
        }
      
        public Lobby getLobby(int i){
            for (Lobby a : this.Lobbys) {
                if (a.getId() == i) {
                    return a;
                }
            }
            return null;
        }
      
        public List<Countrie> getCountries(int id) {
            for (Lobby l : this.Lobbys) {
                if (l.getId() == id) {
                    return l.getCountries();
                }
            }
            return null;
        }
      
        public List<Territorie> getTerritories(int id) {
            for (Lobby l : this.Lobbys) {
                if (l.getId() == id) {
                    return l.getTerritories();
                }
            }
            return null;
        }
      
      
      
      
        public boolean isLobby(int i) {
            if (i <= LobbySize) {
                return true;
            }
            return false;
        }
      
      
        public boolean isInGame(Player p) {
            for (Lobby a : this.Lobbys) {
                if (a.getPlayers().contains(p.getUniqueId()))
                    return true;
            }
            return false;
        }
      
      
      
      
        public Lobby createLobby(Location l,int lobby) {     
          
            Lobby a = new Lobby(l, lobby);
            this.Lobbys.add(a);
    
            return a;
        }
      
        public void addCountrie(Countrie c, int i) {
            Lobby a = this.getLobby(i);
            a.getCountries().add(c);
        }
      
        public void addTerritorie(Territorie t, int i) {
            Lobby a = this.getLobby(i);
            a.getTerritories().add(t);
        }
      
      
      
      
        public void loadLobbySize() {
            int max = 0; int i;
            if (FileLobbys.get().isConfigurationSection("Lobbys")) {
                for (String key: FileLobbys.get().getConfigurationSection("Lobbys").getKeys(true)) {
                    i = Integer.parseInt(key);
                    if (i > max) { max = i; }
                }
                LobbySize = max;
            }
        }
      
        public void loadLobbys () {
            for (int i = 1; i<=LobbySize; i++) {
                this.createLobby(this.deserializeLoc(FileLobbys.get().getString("Lobbys."+i)), i);
              
                CountrieManager.get().loadCountries(this.getLobby(i));
            }
        }
      
      
    
      
        public void addPlayer(Player p, int i) {
            ItemStack compass = U.createItemStack(Material.COMPASS, "&aOpen Menu");
            ItemStack leaveGame = U.createItemStack(Material.REDSTONE_TORCH_ON, "&cLeave Lobby");
            Lobby a = this.getLobby(i);
          
            a.getPlayers().add(p.getUniqueId());
          
            inv.put(p.getUniqueId(), p.getInventory().getContents());
            armor.put(p.getUniqueId(), p.getInventory().getArmorContents());
            p.getInventory().setArmorContents(null);
            p.getInventory().clear();
          
            locs.put(p.getUniqueId(), p.getLocation());
            p.teleport(a.getSpawn());
            p.getInventory().addItem(compass);
            p.getInventory().setItem(8, leaveGame);
        }
      
        public void removePlayer(Player p) {
            Lobby a = null;
    
            // Searches each arena for the player
            for (Lobby l : this.Lobbys) {
                if (l.getPlayers().contains(p.getUniqueId()))
                    a = l;
            }
    
            if (a == null) {
                p.sendMessage("Invalid operation!");
                return;
            }
    
            a.getPlayers().remove(p.getUniqueId());
    
            p.getInventory().clear();
            p.getInventory().setArmorContents(null);
          
            p.getInventory().setContents(inv.get(p.getUniqueId()));
            p.getInventory().setArmorContents(armor.get(p.getUniqueId()));
          
            inv.remove(p.getUniqueId());
            armor.remove(p.getUniqueId());
    
            p.teleport(locs.get(p.getUniqueId()));
            locs.remove(p.getUniqueId());
            p.setFireTicks(0);
            p.updateInventory();
        }
      
        // UTILS
        public String serializeLoc(Location l){
            return l.getWorld().getName() + "," + l.getBlockX() + "," + l.getBlockY() + "," + l.getBlockZ();
        }
    
        public Location deserializeLoc(String s){
            String[] st = s.split(",");
            return new Location(Bukkit.getWorld(st[0]), Integer.parseInt(st[1]), Integer.parseInt(st[2]), Integer.parseInt(st[3]));
        }
    }
    
    Territorie:
    Code:
    package me.kingofmars4.hoc.handlers.territories;
    
    import me.kingofmars4.hoc.handlers.countries.Countrie;
    import me.kingofmars4.hoc.handlers.lobbies.Lobby;
    
    public class Territorie {
      
        private final String name;
        private Countrie owner;
        private int population;
        private final Lobby lobby;
      
        public Territorie (String name, Countrie owner, int population, Lobby lobby) {
            this.name = name;
            this.owner = owner;
            this.population = population;
            this.lobby = lobby;
        }
      
        // GETTERS
        public Countrie getOwner() {
            return this.owner;
        }
      
        public String getName() {
            return this.name;
        }
      
        public int getPopulation() {
            return this.population;
        }
      
        public void setPopulation(int population) {
            this.population = population;
        }
    
        public Lobby getLobby() {
            return lobby;
        }
    }
    
    TerritorieManager:
    Code:
    package me.kingofmars4.hoc.handlers.territories;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.bukkit.Bukkit;
    
    import me.kingofmars4.hoc.files.Gamedata;
    import me.kingofmars4.hoc.handlers.countries.Countrie;
    import me.kingofmars4.hoc.handlers.countries.CountrieManager;
    import me.kingofmars4.hoc.handlers.lobbies.Lobby;
    import me.kingofmars4.hoc.handlers.lobbies.LobbyManager;
    
    public class TerritorieManager {
      
        private static TerritorieManager tm;
        public final List<Territorie> territories = new ArrayList<Territorie>();
      
        private TerritorieManager() {}
      
        public static TerritorieManager get() {
            if (tm == null) {
                tm = new TerritorieManager();
            }
            return tm;
        }
      
        public Territorie getTerritorie(Lobby lobby, String name) {
            for (int i = 0; i<TerritorieManager.get().territories.size(); i++) {
                if (TerritorieManager.get().territories.get(i).getName().equalsIgnoreCase(name)) {
                    return this.territories.get(i);
                }
            }
            return null;
        }
      
        public Countrie getOwner(Lobby lobby, String name) {
            for (int i = 0; i<TerritorieManager.get().territories.size(); i++) {
                if (TerritorieManager.get().territories.get(i).getName().equalsIgnoreCase(name)) {
                    return getTerritorie(lobby, name).getOwner();
                }
            }
            return null;
        }
      
        public int getPopulation(Lobby lobby, String name) {
            for (int i = 0; i<TerritorieManager.get().territories.size(); i++) {
                if (TerritorieManager.get().territories.get(i).getName().equalsIgnoreCase(name)) {
                    return getTerritorie(lobby, name).getPopulation();
                }
            }
            return 0;
        }
      
        public void setPopulation(Lobby lobby, String name, int population) {
            for (Territorie c : this.territories) {
                if (c.getName() == name) {
                    c.setPopulation(population);
                }
            }
        }
      
        public Territorie createTerritorie(String name, Countrie owner, int population, Lobby lobby) {   
          
            Territorie t = new Territorie(name, owner, population, lobby);
            this.territories.add(t);
    
            return t;
        }
    
        public void loadTerritories() {
            for (String key : Gamedata.get().getConfigurationSection("Territories").getKeys(true)) {
                if (!key.contains(".")) {
                    int size = LobbyManager.get().getLobbys().size();
                    for (int i = 1; i<=size; i++) {
                        Countrie c = CountrieManager.get().getCountrie(Gamedata.get().getString("Territories."+key+".Owner"));
                        int population = Gamedata.get().getInt("Territories."+key+".Population");
                        Lobby lobby = LobbyManager.get().getLobby(i);
                      
                        this.createTerritorie(key, c, population, lobby);
                        LobbyManager.get().addTerritorie(this.getTerritorie(lobby, key), i);
                        Bukkit.broadcastMessage("NOME: "+key+" | LOBBY: "+i);
                    }
                }
            }
        }
    }
    
    MAIN:
    Code:
    package me.kingofmars4.hoc;
    
    import org.bukkit.Bukkit;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.Plugin;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
    import me.kingofmars4.hoc.commands.CommandPopulation;
    import me.kingofmars4.hoc.commands.CreateLobby;
    import me.kingofmars4.hoc.commands.DeleteLobby;
    import me.kingofmars4.hoc.commands.Turn;
    import me.kingofmars4.hoc.files.Gamedata;
    import me.kingofmars4.hoc.files.FileLobbys;
    import me.kingofmars4.hoc.guis.SelectCountry;
    import me.kingofmars4.hoc.handlers.lobbies.LobbyManager;
    import me.kingofmars4.hoc.handlers.territories.TerritorieManager;
    import me.kingofmars4.hoc.listeners.CreateSign;
    import me.kingofmars4.hoc.listeners.JoinGame;
    import me.kingofmars4.hoc.listeners.LeaveLobby;
    import me.kingofmars4.hoc.utils.Messages;
    import me.kingofmars4.hoc.utils.U;
    
    public class Main extends JavaPlugin {
     
        public static Plugin plugin; public static Plugin getPlugin(){return plugin;}
     
        @Override
        public void onLoad() {
            loadConfigFiles();
            loadCache();
        }
      
        public void onEnable() {
            plugin = this;
          
            loadCommands();
            loadListeners();
         
            getLogger().info(this.getDescription().getFullName() + " by KingOfMars4 has been enabled!");
        }
     
        @Override
        public void onDisable() {
            saveCache();
        }
     
        public void loadCommands() {
            getCommand("population").setExecutor(new CommandPopulation());
            getCommand("turn").setExecutor(new Turn());
            getCommand("createlobby").setExecutor(new CreateLobby());
            getCommand("deletelobby").setExecutor(new DeleteLobby());
        }
     
        public void loadListeners() {
            PluginManager pm = getServer().getPluginManager();
            pm.registerEvents(new SelectCountry(), this);
            pm.registerEvents(new CreateSign(), this);
            pm.registerEvents(new JoinGame(), this);
            pm.registerEvents(new LeaveLobby(), this);
        }
     
        public void saveCache() {
           
         }
      
        public void loadCache() {
          
            LobbyManager.get().loadLobbySize();
            LobbyManager.get().loadLobbys();
            TerritorieManager.get().loadTerritories();
          
            getLogger().info("Cache data succefully loaded.");
        }
      
        public void loadConfigFiles() {
            Gamedata.setup();
            U.loadDefaults();
            Gamedata.get().options().copyDefaults(true);
            Gamedata.save();
          
            FileLobbys.setup();
            FileLobbys.save();
          
            getLogger().info("Configuration files succefully loaded.");
        }
     
        // COMMANDS
        @Override
         public boolean onCommand(CommandSender sender, Command cmd, String label,  String[] args) {
            Player p = (Player) sender;
            if (cmd.getName().equals("hoc")) { if (args.length>0) { switch(args[0].toLowerCase()) {
                 
                        case "reload":
                            if (p.hasPermission("hoc.reload")) {
                              
                                saveCache();
                                Bukkit.getPluginManager().disablePlugin(this);
                                Bukkit.getPluginManager().enablePlugin(this);
                                p.sendMessage(Messages.pluginPrefix + U.color("&9Config reloaded &asuccessfully&9!"));
                             } else {
                                p.sendMessage(Messages.noPerm);
                            }
                    }
                } else {
                    if (p.hasPermission("hoc.player")) {
                        SelectCountry.updateGUI();
                        p.openInventory(SelectCountry.gui);
                     
                    } else {
                        p.sendMessage(Messages.noPerm);
                    }
                }
                return true;
             }
            return false;
         }
    }
    If you need more classes, just ask.
     
  2. Offline

    KarimAKL

    @KingOfMars4
    Code:Java
    1. Lobby a = this.getLobby(i);
    2. a.getTerritories().add(t);

    'a' is null.
     
  3. Offline

    KingOfMars4

    You rule man.
    Marking as solved.

    EDIT: Re-opening this because I did some testing and apparently this:
    Code:Java
    1. Bukkit.broadcastMessage(""+ TerritorieManager.get().getTerritorie(LobbyManager.get().getLobby(1), "Alaska").getPopulation());
    2. TerritorieManager.get().setPopulation(TerritorieManager.get().getTerritorie(LobbyManager.get().getLobby(1), "Alaska"), 200000);
    3. Bukkit.broadcastMessage(""+ TerritorieManager.get().getTerritorie(LobbyManager.get().getLobby(1), "Alaska").getPopulation());
    4. Bukkit.broadcastMessage(""+ TerritorieManager.get().getTerritorie(LobbyManager.get().getLobby(2), "Alaska").getPopulation());
    5. if (TerritorieManager.get().getTerritorie(LobbyManager.get().getLobby(1), "Alaska") == TerritorieManager.get().getTerritorie(LobbyManager.get().getLobby(2), "Alaska")) {
    6. Bukkit.broadcastMessage("TRUE");
    7. }
    8.  


    Returns this:
    https://prnt.sc/vf8wuz

    The idea was to different lobbys have different territories, but they seem to be the same.
    Any tought?
    [​IMG]

    Bump

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Nov 7, 2020
  4. Offline

    KarimAKL

    @KingOfMars4 Try printing the objects, the hashcode might tell you whether or not it is the same object.
     
  5. Offline

    KingOfMars4

    I did that and i detected that the same one is the territory name, i am thinking in creating a new field for territories called id and identify them by the id and not the name.
     
  6. Offline

    KarimAKL

    What do you mean?

    As long as the names are unique, they can be used as IDs. (take for example Map<String, Object>)
     
  7. Offline

    KingOfMars4

    Problem is that i pretend in using the country names later and I dont wish to have a Germany1, America2 etc.
    But in creating a id, I would need to put it inside the for that loads the countries from the config/db and I would not know the ids that are given to each country at each lobby.

    EDIT:
    Actually got it, if you guys want to know how:
    Instead of using a Countrie/Territorie Manager I used the LobbyManager to manage countries and territories and did a for to with a List<String> of the names of countries/territories to load them.

    Code:
    private final List<String> countriesNames = new ArrayList<String>();
    public void loadLobbySize() {
            int max = 0; int i;
            if (FileLobbys.get().isConfigurationSection("Lobbys")) {
                for (String key: FileLobbys.get().getConfigurationSection("Lobbys").getKeys(true)) {
                    i = Integer.parseInt(key);
                    if (i > max) { max = i; }
                }
                LobbySize = max;
            }
           
            countriesNames.add("USA");
            countriesNames.add("Germany");
        }
       
        public void loadLobbys () {
            for (int i = 1; i<=LobbySize; i++) {
                Lobby l = new Lobby(this.deserializeLoc(FileLobbys.get().getString("Lobbys."+i)), i);
                this.Lobbys.add(l);
               
                for (int o = 1; o<=countriesNames.size(); o++) {
                    addCountrie(countriesNames.get(o-1), i, l);
                }
            }
        }
     
    Last edited: Nov 8, 2020
Thread Status:
Not open for further replies.

Share This Page