Solved Get the data of a config and put in Inventory

Discussion in 'Plugin Development' started by AntonioC94, Mar 24, 2020.

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

    AntonioC94

    Hello there!
    I'm making a teleport plugin for a RPG style.
    So, The problem is that Im not really sure about how to get the data in the config and put the data in a custom inventory (The item on an "slot" and the item with the name ).
    Code:
    Location:
      asd:
        World: world
        X: 196.47117474858277
        Y: 110.0
        Z: -66.62703968091523
        Item: minecraft:granite
    
     
    Last edited: Mar 24, 2020
  2. You can use Material to get an item from config then set it to whoever's inventory you want.

    Code:
    Material.getMaterial(this.getConfig().getString("Location."+player.getName()+".Item")
     
  3. Offline

    AntonioC94

    Thanks for the reply!

    I will explain a litle bit more...
    I save in the config all the stations with a command

    Code:
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            if (sender instanceof Player) {
                Player player = (Player) sender;
                if (cmd.getName().equalsIgnoreCase("polvos")) {
                    if (args.length == 1) {
                        if (args[0].equalsIgnoreCase("ver")) {            }
                    }
                    if (args.length == 2) {
                        if (args[0].equalsIgnoreCase("añadir")) {
                            String nombre = args[1];
                            Location localizacion = player.getLocation();
                            ItemStack item = player.getInventory().getItemInMainHand();
                            if (item != null) {
                                main.getConfig().set("Location." + nombre + ".World", localizacion.getWorld().getName());
                                main.getConfig().set("Location." + nombre + ".X",
                                        Double.valueOf(player.getLocation().getX()));
                                main.getConfig().set("Location." + nombre + ".Y",
                                        Double.valueOf(player.getLocation().getY()));
                                main.getConfig().set("Location." + nombre + ".Z",
                                        Double.valueOf(player.getLocation().getZ()));
                                main.getConfig().set("Location." + nombre + ".Item",
                                        item.getType().getKey().toString());
                                main.saveConfig();                   
                                player.sendMessage("Estación " + nombre + " añadida con exito");
                            } else {
                                player.sendMessage("debes tener un item en la mano");
                            }
                        }
                    }
    
                }
            }
            return true;
        }
    
    So how can i add the value "nombre" (name of the station) in the menu class, to get first the item and then put in the inventory?
     
  4. Offline

    KarimAKL

    @AntonioC94 Loop the keys in "Location" using "getConfig()#getConfigurationSection("Location")#getKeys(false)".
     
  5. Offline

    AntonioC94

    @KarimAKL thanks a lot :D , Now the idea in my mind is get all items and then put into a hashmap and then create a new loop to create the inventory with all the items. What do you think about this?
     
  6. Offline

    KarimAKL

    @AntonioC94 It sounds to me like you could add the items to the inventory in the loop.

    I'm not sure what exactly you want to do, so i can't really help any further with that.
     
  7. Offline

    AntonioC94

    @KarimAKL so, when I do a Right-Click in a flower pot (above bedrock) an inventory is created with all the "warps" saved in the config like this

    [​IMG]

    The problem that I have is..... I don't really know, how can I get the data (Item + name) and make a menu and then put in the inventory . So that is my doubt
     
  8. Offline

    KarimAKL

    @AntonioC94 You should create the inventory and load all the items in the onEnable, that way you won't have to do it everytime a flower pot is clicked.

    If we say the config looks like this:
    Code:YAML
    1. Warps:
    2. warp1:
    3. World: world
    4. X: 106.0
    5. Y: 72.0
    6. Z: -286.0
    7. Yaw: 0.0
    8. Pitch: 0.0
    9. Item:
    10. Material: diamond
    11. Amount: 27
    12. Name: "&rName: {warp}"
    13. Lore:
    14. - "&7Click here to warp to"
    15. - "&a{warp}"


    Something like this should work:
    Code:Java
    1. // Create a list of warps
    2. List<Warp> warps = new ArrayList<>();
    3.  
    4. // Get the config
    5. FileConfiguration config = getConfig();
    6.  
    7. // Get the section "Warps" inside the config
    8. ConfigurationSection warpsSection = config.getConfigurationSection("Warps");
    9.  
    10. // Loop the section's keys
    11. for (String warpName : warpsSection.getKeys(false)) {
    12. // Declare the warp location
    13. Location location = null;
    14.  
    15. // Declare the warp's item in the GUI
    16. ItemStack item = null;
    17.  
    18. // Get the warp's section
    19. ConfigurationSection warpSection = warpsSection.getConfigurationSection(warpName);
    20.  
    21. // Location
    22. {
    23. // Get the location, i didn't do any null checks for the sake of shortening the example
    24. World world = Bukkit.getWorld(warpSection.getString("World"));
    25. double x = warpSection.getDouble("X");
    26. double y = warpSection.getDouble("Y");
    27. double z = warpSection.getDouble("Z");
    28. float yaw = (float) warpSection.getDouble("Yaw");
    29. float pitch = (float) warpSection.getDouble("Pitch");
    30.  
    31. // Set the location
    32. location = new Location(world, x, y, z, yaw, pitch);
    33. }
    34.  
    35. // Item
    36. {
    37. // Get the warp section's item section
    38. ConfigurationSection itemSection = warpSection.getConfigurationSection("Item");
    39.  
    40. // Get the values for the ItemStack constructor
    41. Material material = Material.matchMaterial(itemSection.getString("Material"));
    42. int amount = itemSection.getInt("Amount");
    43.  
    44. // Set the item
    45. item = new ItemStack(material, amount);
    46.  
    47. // Get the item's meta
    48. ItemMeta meta = item.getItemMeta();
    49.  
    50. // Replacements
    51. List<SimpleEntry<String, String>> replacements = new ArrayList<>();
    52. replacements.add(new SimpleEntry("{warp}", warpName));
    53.  
    54. // Set the item's name and lore
    55. meta.setDisplayName(custom(itemSection.getString("Name"), replacements));
    56. meta.setLore(custom(itemSection.getStringList("Lore"), replacements));
    57.  
    58. // Set the item's meta
    59. item.setItemMeta(meta);
    60. }
    61.  
    62. // Add the warp to the list of warps
    63. warps.add(new Warp(warpName, location, item));
    64. }
    65.  
    66. // Below are the methods i use for the name and lore in this example
    67.  
    68. // Customize a string by replacing '&' with '§' (Using ChatColor) and adding replacements such as the warp's name
    69. public String custom(String string, List<SimpleEntry<String, String>> replacements) {
    70. String customized = ChatColor.translateAlternateColorCodes('&', string);
    71.  
    72. for (SimpleEntry<String, String> replacement : replacements) {
    73. customized = customized.replace(replacement.getKey(), replacement.getValue());
    74. }
    75.  
    76. return customized;
    77. }
    78.  
    79. // This method just loops a List<String> and uses the "custom(String, ...)" method on all of the strings inside
    80. public List<String> custom(List<String> list, List<SimpleEntry<String, String>> replacements) {
    81. List<String> customized = new ArrayList<>();
    82.  
    83. for (String string : list) customized.add(custom(string, replacements));
    84.  
    85. return customized;
    86. }


    Note: I haven't tested this code before, i've just written it now.
     
  9. Offline

    AntonioC94

    @KarimAKL thanks for your help a lot!

    Your idea and your code looks great, but I don't really understand how works the List<Warp>, I mean.. creating this list Im saving a location of a x variable , so... how works the List<Warp>? Maybe the List that I need to create is "Location"?

    Edit: I did a litle changes and the code work more or less (thanks again), I have a problem when I add all the variables to the List
    Code:
    estaciones.add(new Location(location, item));
    
    I have the error "The constructor Location(Location, ItemStack) is undefined" . I don't really understand what constructor mean if this code is in onEnable
     
    Last edited: Mar 31, 2020
  10. Offline

    KarimAKL

    No, i just used Warp as an example to hold data for warps.
    How it would look:
    Code:Java
    1. public class Warp {
    2.  
    3. private final String name;
    4.  
    5. private Location location;
    6. private ItemStack item;
    7.  
    8. public Warp(String name, Location location, ItemStack item) {
    9. this.name = name;
    10. this.location = location;
    11. this.item = item;
    12. }
    13. }

    When you call "new SomeClass()", you're calling a constructor, in this case you're trying to call the constructor "Location(Location, ItemStack)", that doesn't exist.
     
  11. Offline

    AntonioC94

    @KarimAKL Wow , all right I understand, you are saving all the data in a class and then calling that method.
    It's a new thing for me sorry hehehe
     
  12. Offline

    KarimAKL

    @AntonioC94 No need to be sorry.

    Let me know if you have any problems.
     
  13. Offline

    Strahan

    Just remember in that code you should be passing defaults. If you try to matchMaterial and you got a null from config, the plugin will puke. I'd pass it barrier or whatever; something that can act as the icon when the configured one is missing or invalid.
     
  14. Offline

    AntonioC94

    @Strahan Hi! , hmmmmm yes, I have problems searching the material from the config (all the time getting null). Maybe
    Code:
    Item: minecraft:granite
    
    is not the best way to get the material , so Im looking for another way to get the material like "GRANITE" and not minecaft:granite
     
  15. Offline

    KarimAKL

    @AntonioC94 You shouldn't add the "minecraft:" part, just "granite" should be fine.
     
  16. Offline

    AntonioC94

    @KarimAKL All Right, By the moment the code works and I have not null .
    So now I just need to get the data and put in the inventory. Just for ask but.. How can I get the data (Location and the item)? I need to call the List<Warp> ? or call the class?

    Edit: (Yes, I didn't remember how to get the item #name() hehe)
     
  17. Offline

    KarimAKL

    @AntonioC94 Create the inventory, then loop the list of warps, and then get the item and add it to the inventory.
     
  18. Offline

    AntonioC94

    My onEnable is fine right?
    Code:
        Points pns;    
    
        public List<Points> estaciones = new ArrayList<>();
    
        public void onEnable() {
            this.inv = new Inventarios(cmd, this, pns);
            this.events = new Eventos(this, inv);
            this.instance = (Plugin) this;
            getLogger().info("está activado y cargado");
            registrarEventos();
            cargarConfiguracion();
            registrarComandos();
    
            FileConfiguration config = getConfig();
            ConfigurationSection estaLoc = config.getConfigurationSection("Location.");
    
            for (String estaNomb : estaLoc.getKeys(false)) {
                Location location = null;
                ItemStack item = null;
                ConfigurationSection estaSec = estaLoc.getConfigurationSection(estaNomb);
                {
                    World world = Bukkit.getWorld(estaSec.getString(".World"));
                    double x = estaSec.getDouble(".X");
                    double y = estaSec.getDouble(".Y");
                    double z = estaSec.getDouble(".Z");
                    location = new Location(world, x, y, z);
                }
                {
                    Material Icono = Material.matchMaterial(estaSec.getString(".Item"));
                    item = new ItemStack(Icono);
                }
                estaciones.add(new Points(location, item));
            }
    
        }
     
    Last edited: Apr 2, 2020
  19. Offline

    KarimAKL

    @AntonioC94 You don't need the '.' when using ConfigurationSection#getConfigurationSection() & ConfigurationSection#get().

    Otherwise, i think it looks good.

    Where are you creating the inventory and adding the items?
     
  20. Offline

    AntonioC94

    @KarimAKL All right jeje I will remove "." .
    So I was testing how can I make the inventory
    Currently this is my inventory class
    Code:
        public void newInventory(Player player) {
          
            Inventory i = main.getServer().createInventory(null, 9, ChatColor.DARK_RED + ("Estaciones"));
          
            ItemStack empty = new ItemStack(pns.item);
            ItemMeta emptyMeta = empty.getItemMeta();
            emptyMeta.setDisplayName("'");
            empty.setItemMeta(emptyMeta);      
    
            i.setItem(0,empty);
          
            player.openInventory(i);
        }
    
    And the point class like this

    Code:
    public class Points {
        
        public Location location;
        public ItemStack item;
    
        public Points(Location location, ItemStack item) {
            this.location = location;
            this.item = item;
        }
    }
    
    Edit: Is not a final code, Im testing hehe
     
    Last edited: Apr 1, 2020
  21. Offline

    KarimAKL

    @AntonioC94 Try adding all of the point items into the inventory, then let me know how it goes.
     
  22. Offline

    AntonioC94

    @KarimAKL So I was trying to get the Item and the location from the data class and I have null , I don't really know.
    Im trying to get the data with the code
    Code:
    main.psn.item
    
    But with null in all cases
     
  23. Offline

    KarimAKL

  24. Offline

    AntonioC94

    @KarimAKL
    Commands
    Code:
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            if (sender instanceof Player) {
                Player player = (Player) sender;
                if (cmd.getName().equalsIgnoreCase("polvos")) {
                    if (args.length == 1) {
                        if (args[0].equalsIgnoreCase("ver")) {            }
                    }
                    if (args.length == 2) {
                        if (args[0].equalsIgnoreCase("añadir")) {
                            String nombre = args[1];
                            Location localizacion = player.getLocation();
                            ItemStack item = player.getInventory().getItemInMainHand();
                            if (item != null) {
                                main.getConfig().set("Location." + nombre + ".World", localizacion.getWorld().getName());
                                main.getConfig().set("Location." + nombre + ".X",
                                        Double.valueOf(player.getLocation().getX()));
                                main.getConfig().set("Location." + nombre + ".Y",
                                        Double.valueOf(player.getLocation().getY()));
                                main.getConfig().set("Location." + nombre + ".Z",
                                        Double.valueOf(player.getLocation().getZ()));
                                main.getConfig().set("Location." + nombre + ".Item",
                                        item.getType().name());
                                main.getConfig().set("Location." + nombre + ".Nombre", nombre);
                                main.saveConfig();                
                                player.sendMessage("Estación " + nombre + " añadida con exito");
                            } else {
                                player.sendMessage("debes tener un item en la mano");
                            }
                        }
                    }
    
                }
            }
            return true;
        }
    
    Main
    Code:
        Plugin instance;
    
        Eventos events;
    
        Inventarios inv;
    
        Points pns;
    
        Comandos cmd;
    
        public List<Points> estaciones = new ArrayList<>();
    
        public void onEnable() {
            this.inv = new Inventarios(cmd, this, pns);
            this.events = new Eventos(this, inv);
            this.instance = (Plugin) this;
            getLogger().info("está activado y cargado");
            registrarEventos();
            cargarConfiguracion();
            registrarComandos();
    
            FileConfiguration config = getConfig();
            ConfigurationSection estaLoc = config.getConfigurationSection("Location.");
    
            for (String estaNomb : estaLoc.getKeys(false)) {
                Location location = null;
                ItemStack item = null;
                ConfigurationSection estaSec = estaLoc.getConfigurationSection(estaNomb);
                {
                    World world = Bukkit.getWorld(estaSec.getString(".World"));
                    double x = estaSec.getDouble(".X");
                    double y = estaSec.getDouble(".Y");
                    double z = estaSec.getDouble(".Z");
                    location = new Location(world, x, y, z);
                }
                {
                    Material Icono = Material.matchMaterial(estaSec.getString(".Item"));
                    item = new ItemStack(Icono);
                }
                estaciones.add(new Points(location, item));
            }
    
        }
    
    Data
    Code:
    public class Points {
      
        public Location location;
        public ItemStack item;
    
        public Points(Location location, ItemStack item) {
            this.location = location;
            this.item = item;
        }
    }
    
    Event to test
    Code:
        public void bloque(PlayerInteractEvent event) {
            if(player.getInventory().getItemInMainHand() != null) {
                player.sendMessage("test" + main.pns.item);
            }
        }
    
    EDIT: How can I put the #code] to java? hehe
     
    Last edited: Apr 2, 2020
  25. Offline

    KarimAKL

    Use [Syntax=Java]Code here[/Syntax] instead of [Code]Code here[/Code]

    As for your code:
    I don't see you initializing "pns" anywhere, that'd cause a NullPointerException.
     
  26. Offline

    AntonioC94

    @KarimAKL Thats was right hehe, Just for ask but.. how can I get the data right know? For example.. Im trying to get the Item saved in the class with "main.psn.item.getType()" or "main.psn.item" but In these cases I have null
     
  27. Offline

    KarimAKL

  28. Offline

    AntonioC94

    The class Points
     
  29. Offline

    KarimAKL

    @AntonioC94 When you use "main.psn.item", do you get "null" or a NullPointerException when printing the value?
     
  30. Offline

    AntonioC94

    @KarimAKL NullPointerException
    Code:
    org.bukkit.event.EventException: null
            at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:320) ~[spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.java:70) ~[spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.java:529) ~[spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.java:514) ~[spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at org.bukkit.craftbukkit.v1_14_R1.event.CraftEventFactory.callPlayerInteractEvent(CraftEventFactory.java:429) ~[spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.PlayerInteractManager.a(PlayerInteractManager.java:432) ~[spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.PlayerConnection.a(PlayerConnection.java:1238) ~[spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.PacketPlayInUseItem.a(PacketPlayInUseItem.java:27) ~[spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.PacketPlayInUseItem.a(PacketPlayInUseItem.java:1) ~[spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.PlayerConnectionUtils.lambda$0(PlayerConnectionUtils.java:19) ~[spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.TickTask.run(SourceFile:18) [spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.IAsyncTaskHandler.executeTask(SourceFile:144) [spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.IAsyncTaskHandlerReentrant.executeTask(SourceFile:23) [spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.IAsyncTaskHandler.executeNext(SourceFile:118) [spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.MinecraftServer.aX(MinecraftServer.java:910) [spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.MinecraftServer.executeNext(MinecraftServer.java:903) [spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.IAsyncTaskHandler.executeAll(SourceFile:103) [spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.MinecraftServer.sleepForTick(MinecraftServer.java:886) [spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at net.minecraft.server.v1_14_R1.MinecraftServer.run(MinecraftServer.java:820) [spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            at java.lang.Thread.run(Unknown Source) [?:1.8.0_221]
    Caused by: java.lang.NullPointerException
            at io.github.shilodabing.PolvosTeleport.Inventarios.newInventory(Inventarios.java:26) ~[?:?]
            at io.github.shilodabing.PolvosTeleport.Eventos.bloque(Eventos.java:37) ~[?:?]
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_221]
            at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_221]
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_221]
            at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_221]
            at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:316) ~[spigot-1.14.4.jar:git-Spigot-9de398a-9c887d4]
            ... 19 more
    
    (Inventarios.java:26)

    Code:Java
    1.  
    2. public void newInventory(Player player) {
    3.  
    4. Inventory i = main.getServer().createInventory(null, 9, ChatColor.DARK_RED + ("Estaciones"));
    5.  
    6. ItemStack item1 = new ItemStack(pns.item); //Null here
    7. ItemMeta meta1 = empty.getItemMeta();
    8. meta1.setDisplayName("'");
    9. item1.setItemMeta(meta1);
    10.  
    11. i.setItem(0,item1);
    12.  
    13. player.openInventory(i);
    14. }
     
Thread Status:
Not open for further replies.

Share This Page