0
public class Common implements Serializable{

    private static HashMap<Integer,List<LevelList>> levelListMap = new HashMap<>();

    public static Map<Integer, List<LevelList>> getLevelListMap(Context context) {

        File file = new File(context.getDir("data", MODE_PRIVATE), "map");
        ObjectInputStream inputStream = null;
        try {
            inputStream = new ObjectInputStream(new FileInputStream(file));
            levelListMap = (HashMap<Integer, List<LevelList>>) inputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return levelListMap;
    } ...
}

I am unable to serialize hashmap.I keep getting java.io.NotSerializableException for levelListMap = (HashMap<Integer, List<LevelList>>) inputStream.readObject();

public class LevelList implements Serializable{

    public int id;
    public String title;
    public String imgurl;
    public String songurl;
    public String songtext;
    boolean isFavourite;

    public void release() {

    }


    public void setFavourite(boolean favourite) {
        isFavourite = favourite;
    }

    public boolean isFavourite(){
        return isFavourite;
    }

}
Sangharsh
  • 2,999
  • 2
  • 15
  • 27
sreejith v s
  • 1,334
  • 10
  • 17

2 Answers2

2

HashMap is serializable, but the keys and values must also be serializable. Make sure that all keys and values are serializable, and that their fields are also serializable (excluding transient and static members).

Edit:

HashMap<Integer,List<LevelList>>, is your List implementation serializable?

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
  • Yes I'm using ArrayList.Will it help ,if I change HashMap> to HashMap> ? – sreejith v s Mar 01 '17 at 11:16
  • @sreejithvs No, it will help if you make `LevelList` implement `Serializable`. Clealry you hadn't done that when you did the serialization, and clearly you ignored the same exception at that point. – user207421 Mar 02 '17 at 04:05
1

Check this link How to serialize a list in Java. Standard implementation of List, i.e. ArrayList, LinkedList, etc. are serializable.

If you declare your List as one of the List subtypes such as ArrayList<LevelList> levelList = new ArrayList<LevelList>(); then it should be serializable out of the box. Otherwise you will need to cast in a safe way, such as setting the List implementation with <T extends List<Foo> & Serializable> setFooList(T list) as suggested by Theodore Murdock in that answer thread.

Community
  • 1
  • 1
themantimes8
  • 71
  • 10