sreejith v s
sreejith v s

Reputation: 1334

Unable to Serialize Hashmap ,java.io.NotSerializableException

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;
    }

}

Upvotes: 0

Views: 822

Answers (2)

Steve Kuo
Steve Kuo

Reputation: 63094

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?

Upvotes: 2

themantimes8
themantimes8

Reputation: 71

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.

Upvotes: 1

Related Questions