Solved Remove string from list

Discussion in 'Spigot Plugin Development' started by cowlk, Feb 2, 2020.

Thread Status:
Not open for further replies.
  1. Basically what I am trying to do is remove a specific string from a string list using a command so for example, my config looks like this:
    Code (Text):
    messages:
    - 'Hello!'
    - 'Good Morning'
    but let's say I don't want 'Good Morning' anymore. I am trying to create a command such as /removestring 1 that would remove 'Good Morning'
    Here is what I have tried so far with no luck:
    Code (Java):
    public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args) {
            if(cmd.getName().equalsIgnoreCase("removestring")) {
                List<String> messages = getConfig().getStringList("messages");
                String x = messages.get(Integer.parseInt(args[0]));
                messages.remove(x);
                saveConfig();
                return true;
            }
           
            return true;
        }
    currently it just removes the ' ' around both strings which is not quite what I am looking for.
     
  2. Choco

    Moderator

    You don't need to get then remove the object. Lists can remove by index so messages.remove(NumberUtils.toInt(args[0])) will work just fine. Note the use of NumberUtils. It returns an int. Integer vs int will call two different methods. You should also consider handling invalid values (specify a negative default and filter out negative values. Give the user feedback) otherwise exceptions will be thrown.

    The reason it's not updating your configuration file is because you've not re-set that value back into the config. Set the list again and it will function as intended. The removal of the parenthesis is because they're unnecessary so SnakeYAML just discards them.
     
  3. Thanks for getting back to me!
    How do I re-set the list?
     
  4. Code (Text):
     getConfig().set("messages", this.messages);
    the same way you would set anything else
     
Thread Status:
Not open for further replies.