【问题标题】:Save hash map Shared Preferences保存哈希映射共享首选项
【发布时间】:2016-04-25 19:25:25
【问题描述】:

我正在尝试将 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();
}

【问题讨论】:

    标签: java android json dictionary sharedpreferences


    【解决方案1】:

    异常告诉你问题出在哪里,你需要从 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);
                }
    

    【讨论】:

    • 谢谢,我试过你的解决方案,效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 2019-04-09
    • 1970-01-01
    • 2019-10-03
    相关资源
    最近更新 更多