保存哈希映射共享首选项

时间:2016-04-25 19:25:26

标签: java android json dictionary sharedpreferences

我想将HashMap保存到SharedPreferences中,但是当我加载地图时出现此错误:

java.lang.ClassCastException:org.json.JSONArray无法强制转换为java.util.List

我调整了我在网上找到的代码,但我不明白为什么会收到此错误。

以下是代码:

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

1 个答案:

答案 0 :(得分:2)

Exception告诉你问题是什么,你需要从JSON获取列表。尝试用这个替换你的while循环:

            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);
            }
相关问题