how to save hashmap with keys as objects to sharedpreferences

226 views Asked by At

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?

2

There are 2 answers

0
Moritz On

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.

1
Helmi On

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();