Reputation: 3
I'm triyng to save an HashMap into SharedPreferences but i get this error when i load the map:
java.lang.ClassCastException: org.json.JSONArray cannot be cast to java.util.List
I adapted the code i found online but i don't understand why i get this error.
Here is the code:
public static Map<String, List<Integer>> loadMap() {
Map<String,List<Integer>> outputMap = new HashMap<>();
SharedPreferences pSharedPref = MainActivity.getContextofApplication().getSharedPreferences(NETWORK_PREF, Activity.MODE_PRIVATE);
try{
if (pSharedPref != null){
String jsonString = pSharedPref.getString(RSSI_MAP, (new JSONObject()).toString());
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<String> keysItr = jsonObject.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
List<Integer> value = (List<Integer>) jsonObject.get(key);
outputMap.put(key, value);
}
}
}catch(Exception e){
e.printStackTrace();
}
return outputMap;
}
public void saveRSSI() {
SharedPreferences pref = MainActivity.getContextofApplication().getSharedPreferences(NETWORK_PREF,Activity.MODE_PRIVATE);
JSONObject jsonObject = new JSONObject(this.RSSImap);
String jsonString = jsonObject.toString();
SharedPreferences.Editor editor = pref.edit();
editor.putString(RSSI_MAP, jsonString);
editor.commit();
}
Upvotes: 0
Views: 250
Reputation:
The Exception is telling you what is the problem, you need to get the list from JSON. Try replacing your while cycle with this one:
while(keysItr.hasNext()) {
String key = keysItr.next();
JSONArray jlist = jsonObject.getJSONArray(key);
List<Integer> list = new ArrayList<>();
for(int i=0; i < jlist.length(); i++){
list.add(jlist.getInt(i));
}
outputMap.put(key, list);
}
Upvotes: 2