Giving a player items defined in a YAML config

Discussion in 'Plugin Development' started by quaz3l, Dec 28, 2011.

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

    quaz3l

    I have a YAML config file which has a list of strings defined with:
    Code:
    String[] listOfStrings = {"3:64", "266:5", "10:1"};
    this.getConfig().set("path.to.list", Arrays.asList(listOfStrings));
    This works fine but when I attempt to retrieve and give a player the defined items and amounts it throws a Null Pointer Exception error in this code when i try retrieving the list:
    Code:
    List<String> items = plugin.getConfig().getStringList("path.to.list");
                PlayerInventory inventory = player.getInventory();
                for(int i=items.size(); i > 0; i++ ) {
                    String current = items.get(i);
                    String[] current_s = current.split(":");
                    Integer howMuch = Integer.parseInt(current_s[1].trim());
                    Integer whatToGive = Integer.parseInt(current_s[0].trim());
                    ItemStack istack = new ItemStack(whatToGive, howMuch);
                    inventory.addItem(istack);
                }
    How can I fix the error and give the player the proper amount of the item specified?
    Is there a better way? If so point me to it.
     
  2. Why not just use list instead of complicating yourself with arrays ?

    I dunno what the null is, could be because you're actually getting a null...

    Another exception might be because you're starting at the end of the array, the last object is size - 1 so you're getting it outside it's range.

    You should do something like this:

    Code:
    List<String> items = cfg.getStringList("path.to.list");
    
    if(items != null && items.size() > 0) // always check against null if it's even the slightest possibility of beeing null
    {
        for(String itemStr : items) // iterate, don't use indexes and .get() for loops !
        {
            // itemStr is the current item as string.
        }
    }
     
  3. Offline

    quaz3l

    Sorry, the null is thrown when I try to define the List<String>.

    Also when I try to define the List in the config I get a Illegal Argument Exeception.
    Code:
    Code:
    this.getConfig().set("path.to.list", listOfStrings);
    Thanks for your help.

    EDIT:

    I also tried to define listOfStrings like this but it still gave me an error when I try to put them in a list variable:
    Code:
    List<String> listOfStrings = new ArrayList<String>();
                listOfStrings.add("25:2");
                listOfStrings.add("3:64");
                listOfStrings.add("266:4");
     
Thread Status:
Not open for further replies.

Share This Page