Plugin Help JavaNullPointerException problem

Discussion in 'Plugin Help/Development/Requests' started by brunodm99, Aug 16, 2016.

Thread Status:
Not open for further replies.
  1. The following code gives me a problem:

    I checked if I get it in 'i' some null value, but it is not, even so receipt 'JavaNullPointerException' in line
    'if(plugin.getPropertiesKit().getString(plugin.getPropertiesKit().getString("Kits."+i.next()+".name")).equalsIgnoreCase(kit))'



    Code:
        public void darKit(Player p, String kit, String[] kits){ //kit --> diamante
            List<String> listaKits = new ArrayList<String>();
           
            listaKits.addAll(plugin.getPropertiesKit().getConfigurationSection("Kits").getKeys(false));
            Iterator<String> i = listaKits.iterator();
    
            //I check if 'i' does not receive null values, printing each value on the server.
    
            while(i.hasNext()){
                  p.sendMessage(i.next());
            }
           //Finished my check
    
            p.sendMessage(plugin.getPropertiesKit().getString("Kits.kit1.name")); //This does not receive null values
            while(i.hasNext()){
                try{
                    if(plugin.getPropertiesKit().getString(plugin.getPropertiesKit().getString("Kits."+i.next()+".name")).equalsIgnoreCase(kit)){   //Give me NullPointerException
                        int a = plugin.getPropertiesKit().getInt("Kits."+i.next()+".numberOfItems");
                        String[] items = new String[a];
                        int k = 0, m = 1;
                        for(int j = 0;j <= a;j++){
                            items[k] = plugin.getPropertiesKit().getString("Kits."+i+".item"+m);
                        }
                        int l = 0;
                        for(int h = 0;h <= a;h++){
                            ItemStack miItem = new ItemStack(Material.valueOf(items[l]));
                            p.getInventory().addItem(miItem);
                            p.sendMessage("[PrimerPlugin] Has recibido el kit "+ChatColor.AQUA+kit);
                            l++;
                        }
                    }else{
                        plugin.getLogger().info("[PrimerPlugin] Error ");
                        break;
                    }
                }catch(Exception e){
                    p.sendMessage(e.getMessage());
                }
            }
        /*    ItemStack miItem = new ItemStack(Material.DIAMOND, 64);
            p.getInventory().addItem(miItem);
            p.sendMessage("Has recibido el kit "+ChatColor.GREEN+kit);        */
           }
     
  2. @brunodm99
    My guess is that the plugin variable is null. Can you show me where you define it?
     
  3. I have it defined in the constructor of the same class
    Code:
    private final Main plugin;
    
    public comandos(Main instance){
           plugin = instance;
    }
    Where Main is my main class, that is where I have the onEnable and onDisable methods.
     
  4. Offline

    timtower Administrator Administrator Moderator

  5. Here is:
    Code:
    package com.gmail.bruno.primerpluginmc;
    
    import java.io.File;
    import java.io.InputStream;
    import java.util.logging.Level;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.event.Listener;
    import org.bukkit.permissions.Permission;
    import org.bukkit.plugin.java.JavaPlugin;
    import org.bukkit.scoreboard.DisplaySlot;
    import org.bukkit.scoreboard.Objective;
    import org.bukkit.scoreboard.Scoreboard;
    import org.bukkit.scoreboard.ScoreboardManager;
    
    public class Main extends JavaPlugin implements Listener{
      
        public static Main instance; //con esto podemos aceder a la clase Main creando un constructor con parametro (Main instance) en cada clase con la instruccion plugin = instance y para acceder a los atributos usamos plugin.atributo
        public  Scoreboard board;
        public  Permission perm_owner = new Permission("primerpluginmc.owner"); //Declaramos el permiso
      
        private FileConfiguration dataKit = null;
        private File dataKitFile = null;
      
        private FileConfiguration dataPlayer = null;
        private File dataPlayerFile = null;
      
        private FileConfiguration propertiesKit = null;
        private File propertiesKitFile = null;
    
        public String colorear(String str){
            return ChatColor.translateAlternateColorCodes('&', str); //translateAlternateColorCodes transforma &6 y &b del archivo config.yml a color
        }
      
        @Override
        public void onLoad(){
            this.getLogger().info("El plugin ha sido cargado");
        }
      
        @Override
        public void onEnable(){
            instance = this;
            File config = new File(getDataFolder()+File.separator+"config.yml");
            if(!config.exists()){
                getConfig().options().copyDefaults(true);
                saveConfig();
            }
          
            File players = new File(getDataFolder()+File.separator+"dataPlayer.yml");
            if(!players.exists()){
                try{
                    reloadDataPlayer();
                    saveDataPlayer();
                }catch (Exception e){
                    this.getLogger().log(Level.SEVERE, "No se ha podido guardar "+dataPlayerFile, e);
                }
            }
          
            File kits = new File(getDataFolder()+File.separator+"kits.yml");
            if(!kits.exists()){
                try{
                    reloadDataKit();
                    saveDataKit();
                }catch(Exception e){
                    this.getLogger().log(Level.SEVERE, "No se ha podido guardar "+dataKitFile, e);
                }
            }
          
            File propertiesKits = new File(getDataFolder()+File.separator+"propertiesKits.yml");
            if(!propertiesKits.exists()){
                try{
                    reloadPropertiesKit();
                    savePropertiesKit();
                }catch (Exception e){
                    this.getLogger().log(Level.SEVERE, "No se ha podido guardar "+propertiesKitFile, e);
                }
            }
          
            setupScoreboard();
            this.getServer().getPluginManager().registerEvents(new WorldListener(instance), instance); //Tambien hay que darle el scoreboard en los eventos de jugador al entrar al juego
          
            this.getLogger().info(getConfig().getString("bienvenida")); //Imprime la bienvenida del config.yml
          
            this.getServer().getPluginManager().addPermission(perm_owner); //Añadimos el peemiso al plugin
          
            this.getServer().getPluginManager().registerEvents(new PlayerListener(instance), instance);
          
            this.getCommand("kit").setExecutor(new comandos(this));
            this.getCommand("sql").setExecutor(new comandos(this));
            this.getCommand("tutorial").setExecutor(new comandos(this));
            this.getCommand("config").setExecutor(this); //Este comando lo pongo aqui porque la declaracion del archivo cnfig.yml la puse aqui, donde es recomendado
          
            this.getLogger().info("El plugin ha sido activado");
          
        }
      
        @Override
        public void onDisable(){
            this.getLogger().info("El plugin ha sido desactivado");
            this.getLogger().info(getConfig().getString("otros.despedida")); //Imprime la despedida dentro de otros del config.yml
        }
      
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
          
            if(label.equalsIgnoreCase("config")){
             if(args.length >= 1){  
                if(args[0].equalsIgnoreCase("set")){
                    boolean a = getConfig().getBoolean("comando.boolean");
                    getConfig().set("comando.boolean", !a);
                    saveConfig(); //Siempre poner esto
                  
                    sender.sendMessage(colorear(getConfig().getString("comando.mensaje") + a)); //colorear llama al metodo declarado arriba                                                                                              
                }else if(args[0].equalsIgnoreCase("get")){
                    sender.sendMessage(ChatColor.AQUA+"La configuracion del plugin tiene el valor de "+ChatColor.GRAY+getConfig().getBoolean("comando.bolean"));
                }
            }else{
                sender.sendMessage("No has escrito argumentos");
            }
           }
            return true;
        }
      
        public void setupScoreboard(){
            ScoreboardManager manager = Bukkit.getScoreboardManager();
            board = manager.getNewScoreboard();
          
            Objective objetivo = board.registerNewObjective("bloques", "dummy"); //http://minecraft-es.gamepedia.com/Marcador#Objetivos para ver el criterio de suma de puntos (2do argumento )
            objetivo.setDisplayName("Bloques rotos");
            objetivo.setDisplaySlot(DisplaySlot.SIDEBAR); //http://minecraft-es.gamepedia.com/Marcador#Slots_mostrados para ver donde se muestra el scoreboard
        }
    
    
      
        @SuppressWarnings("deprecation")
        public void reloadDataKit(){
            if(dataKitFile == null){
                dataKitFile = new File(getDataFolder(),"kits.yml");
            }
            dataKit = YamlConfiguration.loadConfiguration(dataKitFile);
          
            InputStream defStream = getResource("kits.yml");
            if(defStream != null){
                YamlConfiguration yamlData = YamlConfiguration.loadConfiguration(defStream);
                dataKit.setDefaults(yamlData);
            }
        }
    
        public FileConfiguration getDataKit(){
            if(dataKit == null){
                this.reloadDataKit();
            }
            return dataKit;
        }
    
        public void saveDataKit(){
            if(dataKit == null || dataKitFile == null){
                return;
            }
            try{
                getDataKit().save(dataKitFile);
            }catch(Exception e){
                this.getLogger().log(Level.SEVERE, "No se ha podido guardar "+dataKitFile, e);
            }
        }
    
      
      
        @SuppressWarnings("deprecation")
        public void reloadDataPlayer(){
            if(dataPlayerFile == null){
                dataPlayerFile = new File(getDataFolder(),"dataPlayer.yml");
            }
            dataPlayer = YamlConfiguration.loadConfiguration(dataPlayerFile);
          
            InputStream defStream =getResource("dataPlayer.yml");
            if(defStream != null){
                YamlConfiguration yamlData = YamlConfiguration.loadConfiguration(defStream);
                dataPlayer.setDefaults(yamlData);
            }
        }
      
        public FileConfiguration getDataPlayer(){
            if(dataPlayer == null){
                this.reloadDataPlayer();
            }
            return dataPlayer;
        }
     
        public void saveDataPlayer(){
            if(dataPlayer == null || dataPlayerFile == null){
                return;
            }
            try{
                getDataPlayer().save(dataPlayerFile);
            }catch(Exception e){
                this.getLogger().log(Level.SEVERE, "No se ha podido guardar "+dataPlayerFile, e);
            }
        }
    
      
        @SuppressWarnings("deprecation")
        public void reloadPropertiesKit(){
            if(propertiesKitFile == null){
                propertiesKitFile = new File(getDataFolder(),"propertiesKits.yml");
            }
            propertiesKit = YamlConfiguration.loadConfiguration(propertiesKitFile);
          
            InputStream defStream = getResource("propertiesKits.yml");
            if(defStream != null){
                YamlConfiguration yamlData = YamlConfiguration.loadConfiguration(defStream);
                propertiesKit.addDefaults(yamlData);
            }
        }
      
        public FileConfiguration getPropertiesKit(){
            if(propertiesKit == null){
                this.reloadPropertiesKit();
            }
            return propertiesKit;
        }
      
        public void savePropertiesKit(){
            if(propertiesKit == null || propertiesKitFile == null){
                return;
            }
            try{
                getPropertiesKit().save(propertiesKitFile);
            }catch(Exception e){
                this.getLogger().log(Level.SEVERE, "No se ha podido guardar "+propertiesKitFile, e);
            }
        }
      
      
    }
    And this is the comandos class, the class that give me the NullPointerException:

    Code:
    package com.gmail.bruno.primerpluginmc;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.inventory.ItemStack;
    
    
    public class comandos implements CommandExecutor{
       
        private Main plugin;
       
        public comandos(Main instance){
            plugin = instance;
        }
       
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            if(label.equalsIgnoreCase("tutorial")){
                Player p = null;
                darKit(p,"diamante",null);
                /* Asi se añaden los permisos
               
                if (sender.hasPermission(plugin.perm_owner)){
                   
                }*/
            }else if(label.equalsIgnoreCase("sql")){
                    PlayerListener pl = new PlayerListener(plugin);
                    pl.guardarDatos("TheBruno", 5);
                    sender.sendMessage("Ingresado");
                   
            }else if(label.equalsIgnoreCase("kit")){
                int numberKits = plugin.getPropertiesKit().getInt("Kits.numberOfKits");
                String[] kits = new String[numberKits];
               
                String kitSelected;
               
                if(args.length > 0){
                    if(args[0].equalsIgnoreCase("diamante")){
                    kits = guardarDatos(numberKits,kits);
                    kitSelected = args[0];
                   
                    //Recorro el array que contiene los nombres de los kits para comprobar cual es igual a kitSelected que contiene el kit introducido por el jugador
                    int q = 0;
                    boolean d = true;
                    int n = 1;
                    for(int g=0; g < kits.length;g++){
                        if(!kits[q].equalsIgnoreCase(kitSelected) || kits[q].equalsIgnoreCase(kitSelected)){
                                if(sender instanceof Player){
                                    Player p = (Player) sender;
                                    darKit(p,args[0],kits);
                                }else{
                                    sender.sendMessage("[PrimerPlugin] Este comando solo lo puede ejecutar un jugador");
                                    sender.sendMessage("[PrimerPlugin] Los kits disponibles son");
                                    break;
                                }
                        }else{
                            while(d){
                                for(int i=1; i <= numberKits; i++){
                                    String a = "Kits.kit"+n+".name";
                                    sender.sendMessage("[PrimerPlugin] "+plugin.getPropertiesKit().getString(a));
                                    //Aqui acaba de imprimir los nombres de los kits
                                    n++;
                                }
                                sender.sendMessage(args[0]);
                                d = false;
                            }
                        }
                        q++;
                    }
                    }
                    //Aqui acaba el recorrido
                       
                        }else if(args.length == 0){
                            int n = 1;
                            //Bucle for para imprimir en el chat el nombre de todos los kits de propertiesKits.yml
                            for(int i=1; i <= numberKits; i++){
                            String a = "Kits.kit"+n+".name";
                            sender.sendMessage("[PrimerPlugin] "+plugin.getPropertiesKit().getString(a));
                            //Aqui acab de imprimir los nombres de los kits
                            n++;
                        }
                        }
                    }
            return true; //Si lo cambio a false, se imprimira el comnado introducido como si se tratase de un mensaje
               
            }
       
        public void darKit(Player p, String kit, String[] kits){ //kit --> diamante
            List<String> listaKits = new ArrayList<String>();
           
            listaKits.addAll(plugin.getPropertiesKit().getConfigurationSection("Kits").getKeys(false));
            Iterator<String> i = listaKits.iterator();
    
            p.sendMessage(plugin.getPropertiesKit().getString("Kits.kit1.name"));
            while(i.hasNext()){
                try{
                    if(plugin.getPropertiesKit().getString(plugin.getPropertiesKit().getString("Kits."+i.next()+".name")).equalsIgnoreCase(kit)){   //Give me NullPointerException
                        int a = plugin.getPropertiesKit().getInt("Kits."+i.next()+".numberOfItems");
                        String[] items = new String[a];
                        int k = 0, m = 1;
                        for(int j = 0;j <= a;j++){
                            items[k] = plugin.getPropertiesKit().getString("Kits."+i+".item"+m);
                        }
                        int l = 0;
                        for(int h = 0;h <= a;h++){
                            ItemStack miItem = new ItemStack(Material.valueOf(items[l]));
                            p.getInventory().addItem(miItem);
                            p.sendMessage("[PrimerPlugin] Has recibido el kit "+ChatColor.AQUA+kit);
                            l++;
                        }
                    }else{
                        plugin.getLogger().info("[PrimerPlugin] Error ");
                        break;
                    }
                }catch(Exception e){
                    p.sendMessage(e.getMessage());
                }
            }
        /*    ItemStack miItem = new ItemStack(Material.DIAMOND, 64);
            p.getInventory().addItem(miItem);
            p.sendMessage("Has recibido el kit "+ChatColor.GREEN+kit);        */
           }
               
        public String[] guardarDatos(int numberKits, String[] kits){
            int k = 0;
            int m = 1;
            //Bucle for que almacena en el array kits el nombre de todos los kits de propertiesKits.yml
            for(int j=1; j <= numberKits; j++){
                String a = "Kits.kit"+m+".name";
                kits[k] = plugin.getPropertiesKit().getString(a);
                m++;
                k++;
            }
            return kits;
        }
      
    }
     
  6. Offline

    timtower Administrator Administrator Moderator

    @brunodm99 No need to log in onLoad
    No need to log in onEnable and onDisable either.

    Try debugging to find what is null
     
  7. I think the problem is in the list 'listaKits' that not obtains data from 'plugin.getPropertiesKit ().getConfigurationSection("Kits").getKeys(false)' because when I call 'p.sendMenssage (listaKits.get (0))' I receive the null point
     
  8. Offline

    timtower Administrator Administrator Moderator

  9. If so, why the list does not obtain the data?
     
  10. Offline

    timtower Administrator Administrator Moderator

  11. Yes, here is my config:

    Code:
    Kits:
        numberOfKits: 2
        kit1:
            numberOfItems: 5   
            name: diamante
            contents:
                item1: DIAMOND_HELMET
                item2: DIAMOND_CHESTPLATE
                item3: DIAMOND_LEGGINS
                item4: DIAMOND_BOOTS
                item5: DIAMOND_SWORD
        kit2:
            numberOfItems: 5
            name: hierro
            contents:
                item1: IRON_HELMET
                item2: IRON_CHESTPLATE
                item3: IRON_LEGGINS
                item4: IRON_BOOTS
                item5: IRON_SWORD
     
Thread Status:
Not open for further replies.

Share This Page