2016-04-25 222 views
0

我triyng保存一个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(); 
} 

回答

2

唯一的例外是告诉你有什么问题,你需要从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); 
      } 
+0

谢谢你,我试过你的解决方案,它的工作完美。 –