Reputation: 1334
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
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
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