Reputation: 8129
I want to set some objects as key of hashmap.And i need to save this hashmap to shared preferences. Given below is my code.
public void saveDetailsMap(MyModel model, int type) {
HashMap<NVRModel, Integer> ipMap = getAddressMap();
ipMap.put(nvrModel, type);
JSONObject jsonObject = new JSONObject(ipMap);
String jsonString = jsonObject.toString();
settings.edit().putString(MAP, jsonString).commit();
}
public HashMap<MyModel, Integer> getAddressMap() {
HashMap<MyModel, Integer> ipMap = new HashMap<MyModel, Integer>();
try {
String jsonString = settings.getString(MAP,
(new JSONObject()).toString());
JSONObject jsonObject = new JSONObject(jsonString);
Iterator keysItr = jsonObject.keys();
while (keysItr.hasNext()) {
MyModel key = (MyModel)keysItr.next();
Integer value = (Integer) jsonObject.get(key.toString());
ipMap.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}
return ipMap;
}
But i am getting this exception
java.lang.ClassCastException: com.model.MyModel cannot be cast to java.lang.String
in below line.
JSONObject jsonObject = new JSONObject(ipMap);
How can i resolve this?
Upvotes: 0
Views: 202
Reputation: 10352
The key of a javascript object has to be of type String. Therefore you can not use HashMap<NVRModel, Integer> ipMap
as the constructor argument of a JSONObject.
Upvotes: 0
Reputation: 556
The hasmap must be of type String only to be valide. otherwhise you can't save it, this what caused the error. what you can do instead is use a file to save your data using ObjectOutputStream.
File file = new File(getDir("data", MODE_PRIVATE), "map");
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
outputStream.writeObject(map);
outputStream.flush();
outputStream.close();
Upvotes: 1