Solved Config: Get Map with Map Value

Discussion in 'Spigot Plugin Development' started by Fabian_Amundsen, May 31, 2021.

  1. Every time when a new player joins, who has never joined before, I want to add a new key for the player with other keys like money or rank to a list in my config.yml.
    The YAML file should then look like this:

    Code (YAML):
    players:
      Player1
    :
       Money:50
        Rank:5
      Player2
    :
       Money:0
        Rank:1
    I check if its a new player with:
    Code (Java):
    Configuration config = Money.getInstance().getConfig();
    Player p = e.getPlayer();
    if(config.get("players."+ p.getName()) != null){
         e.setJoinMessage(ChatColor.YELLOW + p.getName() + " joined the server!");
         }
    In "else" it should now add a new player to the config by getting the map, adding a new item and setting the value of "players" to that new map. I tried it with
    Code (Text):
    getMapList("players")
    but it seems like the HashMap type isnt compatible with a map with a map as value. Or can I just cast that?
     
  2. Ymerejliaf

    Benefactor

    Hey @Fabian_Amundsen,

    So just a couple things here. First, I would recommend using Player#getUniqueId() instead of Player#getName() and then store the UUID in your YML file instead of their name. The reason for this is because if the player changes their name (since Minecraft allows you to change your username) then when they join the server with their new name, they suddenly now have a brand new config. If you wanted them to have their old config, then you'd have to go into your file and manually change the name of their old config and delete the one that was just created so that the player has their old rank and money values.
    The UUID does not change when the player changes their username, so you have more persistent data by using the Unique ID instead of the Name and don't have to worry about name changes.

    With regards to the getMapList method, have you looked at this thread? https://www.spigotmc.org/threads/getconfig-getmaplist-seems-to-return-an-empty-list.374536/

    As far as your actual Map object goes, in order to not have to cast it, I would recommend programming to the Interface, so doing something like this (though in your case you may need to use Integers if all you're storing is numbers):
    Code (Java):
    Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
    You will however run into a potentially different issue with this. If you just blindly run something like:
    Code (Java):
    map.get("keyname").get("nestedkeyname");
    If "keyname" doesn't exist, you will get a NullPointerException. So you may also want to have a check using Map#containsKey().

    I hope that helps a bit though!
     
    • Agree Agree x 1
  3. Yup, this well help me, thanks for your quick response!
     
  4. Better use MySQL