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();
}
謝謝你,我試過你的解決方案,它的工作完美。 –