Solved Save the inventory and give it back to the player

Discussion in 'Plugin Development' started by Muxon, Dec 28, 2012.

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

    Muxon

    Hello there,
    I began to write a little plugin for a server of a friend of mine. It is supposed to get the inventory of the player on command and then save it to a file. After that the player can go to a second server and fetch his/her inventory there on command.

    My Problem is the saving part. As of now i got the following:
    Code:
        public void fillHashmap(Player player){
            PlayerInventory inv = player.getInventory();
            ItemStack[] stack = inv.getContents();
            HashSet<ItemStack> itemList = new HashSet<ItemStack>();
           
            for(int y = 0; y < stack.length; y++){
                if(stack[y] != null){
                    itemList.add(stack[y].getData().toItemStack(stack[y].getAmount()));
                    inv.remove(stack[y]);
                }
            }
            plugin.map.put(player.getName(), itemList);
            save(plugin.map, plugin.path);
        }
    The save method is the one from the bukkit wiki for hashmaps.
    So when I try to save the hashmap there is a error: "notSeriazableException". So is there any other way of getting the EXACT item id to prevent causing this error?

    Second thing is that normal potions are changing to splash potions atm... how to solve this error?
    Thanks in advance,
    Muxor
     
  2. Offline

    MP5K

    hello Muxon,
    you can't serialize an Itemstack but you can serialize Strings/int etc.
    so i created an little wrapper for you.
    I haven't tested it but it should work fine.
    You can also save HashMaps / Lists of this class.
    (btw: Please message me / post it here if an error occurs.
    PHP:
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map.Entry;
     
    import org.bukkit.enchantments.Enchantment;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.material.MaterialData;
     
    public final class 
    SaveItemStack implements Serializable {
     
        
    /**
        *
        */
        
    private static final long serialVersionUID = -3786037251179122333L;
       
        private 
    Integer AMOUNT null;
        private 
    Integer ID null;
        private 
    Short DURABILLITY null;
        private 
    String META_DISPLAYNAME null;
        private List<
    StringMETA_LORE null;
        private 
    Byte META_DATA null;
       
        private 
    HashMap<String IntegerENCHANTMENTS = new HashMap<String Integer>();
       
        public 
    SaveItemStack(ItemStack raw){
            
    this.AMOUNT raw.getAmount();
            
    this.ID raw.getTypeId();
            
    this.DURABILLITY raw.getDurability();
            
    this.META_DISPLAYNAME raw.getItemMeta().getDisplayName();
            
    this.META_LORE raw.getItemMeta().getLore();
           
            for(
    Entry<Enchantment Integerraw.getEnchantments().entrySet()){
                
    this.ENCHANTMENTS.put(e.getKey().getName(), e.getValue());
            }
           
            
    this.META_DATA raw.getData().getData();
        }
       
        public 
    ItemStack getItemStack(){
            
    ItemStack stack = new ItemStack(ID AMOUNT);
            
    stack.setDurability(this.DURABILLITY);
            
    ItemMeta temp_item stack.getItemMeta();
              
    temp_item.setDisplayName(META_DISPLAYNAME);
              
    temp_item.setLore(META_LORE);
            
    stack.setItemMeta(temp_item);
           
            for(
    Entry<String Integerthis.ENCHANTMENTS.entrySet()){
                
    stack.addEnchantment(Enchantment.getByName(e.getKey()), e.getValue());
            }
           
            
    MaterialData temp_mat stack.getData();
              
    temp_mat.setData(this.META_DATA);
            
    stack.setData(temp_mat);
           
            return 
    null;
        }
       
        public 
    void save(File file){
            try
              {
              
    FileOutputStream fileOut = new FileOutputStream(file);
              
    ObjectOutputStream out = new ObjectOutputStream(fileOut);
              
    out.writeObject(this);
              
    out.close();
              
    fileOut.close();
              }catch(
    IOException i){  i.printStackTrace(); }
            }
       
        public static 
    SaveItemStack load(File file){
            try{
            
    FileInputStream fileIn = new FileInputStream(file);
            
    ObjectInputStream in = new ObjectInputStream(fileIn);
            
    SaveItemStack sfile =  (SaveItemStackin.readObject();
            
    in.close();
            
    fileIn.close();
            return 
    sfile;
            }catch(
    Exception e){e.printStackTrace();}
            return 
    null;
           
        }
    }
     
    MisterErwin and Major_Derp like this.
  3. Offline

    Muxon

    Okay first of all thank you for this! It is just great and works great:)
    My problem now is that i don't really know how to give the items back to the player when reloading...
     
  4. Offline

    xXSilentYoshiXx

    You could make a command where it could reset the player's inventory to when you saved it.

    Maybe the code could look like this:

    Code:
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
        Player player = (Player) sender;
        if (commandLabel.equalsIgnoreCase("resetinventory") || commandLabel.equalsIgnoreCase("resetinv")) {
            Player targetPlayer = Player.getServer().getPlayer(args[0]);
            targetPlayer.[Whatever code goes here, figure it out. Make it find the ArrayList and set the inventory to that ArrayList]
        }
    }
     
  5. Offline

    Muxon

    I know how to add the things, the exact problem is how to get all the SaveItemStack objects from the file I saved them to.
     
  6. Offline

    Major_Derp

    I could help with adding the stuff back to the inventory, but i use a slightly different method than MP5K did, His code is good though, but i just do it a different way.
    Let me get the code if you want it
     
  7. Offline

    Muxon

    Major_Derp would be great if you share it with me (us) :)
     
  8. Offline

    Major_Derp

    Muxon
    First declare this somewhere at the beginning of your file
    Code:java
    1.  
    2. public HashMap<Player, ItemStack[]> itemhash = new HashMap<Player, ItemStack[]>();
    3.  

    Now here is the part to add to fill the hashmap, and this part is not completley set up for use in a command class, so you would have to change up some of the variable, but for the most part it should work.
    Code:java
    1.  
    2. ItemStack[] playerinv = player.getInventory().getContents();
    3. public HashMap<Player, ItemStack[]> itemhash = new HashMap<Player, ItemStack[]>();
    4. itemhash.put(player, playerinv);
    5.  

    Now on the command to restore the players inventory here is the part, and remeber, it will require some slight modification to work for the command class too, but in general i think it should work.
    Code:java
    1.  
    2. if(itemhash.containsKey(player)){
    3. ItemStack[] items = itemhash.get(player);
    4. PlayerInventory inv = player.getInventory();
    5. for(ItemStack item : items){
    6. player.getInventory().addItem(item);
    7. }
    8. }
    9.  

    hopefully this should all work, if you need more help on this stuff, just pm me, and im just a begenning programmer, so i hope it works, i hope im not horribly wrong XD
     
  9. Offline

    fireblast709

    What are people trying to do with all this serializable and stuff, while ItemMeta implements ConfigurationSerializable. This means it should be just fine to use the get and set of Bukkit's configuration classes...
     
  10. Offline

    Muxon

    Yep this works, but the problem with this is that you can't save this to a .bin-file or something because ItemStack[] is a not seriaziable type.

    fireblast709 I allready managed this i just want to know how to get all the SaveItemStack objects i saved to the file when i try to add the items back to the players inventory

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 30, 2016
  11. Offline

    Major_Derp

    I wouldnt know what to do for that, im still just beginning, i still have much to learn XD, hope i helped you though.
     
  12. Offline

    fireblast709

    Not a clue and not going to bother :p. You can just get the inventory contents, someConfig.set("Path", ItemStack) it, and get it back using (ItemStack)someConfig.get("Path");. Probably something like this in pseudo (more like: there is a chance it is incorrect):
    Saving:
    Code:java
    1. ItemStack[] inv = player.getInventory().getContents();
    2. List<ItemStack> invList = (List<ItemStack>)Arrays.asList(inv);
    3. someConfig.set("Inventories."+player.getName(), invList);

    Retrieving:
    Code:java
    1. List<ItemStack> savedInv = List<ItemStack>someConfig.get("Inventories."+player.getName());
    2. ItemStack[] inv = savedInv.toArray(new ItemStack[1]{new ItemStack(Material.AIR, 1)});
    3. player.getInventory().setContents(inv);
    As I said, highly likely that it wont work and you would have to save the ItemStacks separate instead of as a List.
     
  13. Offline

    Muxon

    That was my alternative ;)
    Thank you! :)
    MP5K if you can answer me how to get all the SaveItemStack objects please let me know
     
  14. Offline

    MP5K

    PHP:
    public HashMap<String SaveItemStack[]> ITEMS = new HashMap<String SaveItemStack[]>(); // to Store the Player name and the Inventory Content
     
    public void save(HashMap<String SaveItemStack[]> items File file){
      
    FileOutputStream f = new FileOutputStream(file); 
      
    ObjectOutputStream s = new ObjectOutputStream(f);         
      
    s.writeObject(items);
      
    s.flush();
      
    s.close();
      
    f.close();
    }
     
    public 
    HashMap<String SaveItemStack[]> load(File file){
      
    HashMap<String SaveItemStack[]> temp,
      
    FileInputStream f = new FileInputStream(file); 
      
    ObjectInputStream s = new ObjectInputStream(f); 
      
    temp = (HashMap<String,SaveItemStack[]>)s.readObject();       
      
    s.close();
      
    f.close();
    }
     
    //To save the HashMap: save(ITEMS , new File("invetory.bin"));
    //To load: ITEMS = load(new File("inventory.bin"));
     
    //To Apply:
    for(SaveItemStack s ITEMS.get(player.getName()){
      
    player.addItem(s.getItemStack());
    }
     
    //To Save the Inventory in A SaveItemStack[]:
    public SaveItemStack[] toSaveItemStack(ItemStack[] items){
      
    SaveItemStack[] temp = new SaveItemStack[items.length];
      for(
    int i items.lengthi++){
        
    temp[i] = new SaveItemStack(items[i]);
      }
      return 
    temp;
    }
     
    MisterErwin likes this.
  15. Offline

    Muxon

    Seriously I love you <3
    Thanks... :3
     
Thread Status:
Not open for further replies.

Share This Page