我想从sharedpreferences存储和检索hashmap,但我在检索数据时遇到了麻烦。代码段如下:
public void saveItemIds(Context context, HashMap<String,Integer> Ids) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(profileIds);
editor.putString(KEY, jsonFavorites);
editor.apply();
}
public HashMap<String,Integer> getIds(Context context) {
SharedPreferences settings;
HashMap<String,Integer> Ids = new HashMap<>();
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(KEY)) {
String jsonFavorites = settings.getString(KEY,null);
Gson gson = new Gson();
//我在这做什么? //
}
return Ids;
}
答案 0 :(得分:0)
您可以将HashMap保存在文件中,并在需要时进行提取。
这样的事情:
public void serializeMap(HashMap<String,String> hm) {
try {
FileOutputStream fStream = openFileOutput(namefile.bin, Context.MODE_PRIVATE) ;
ObjectOutputStream oStream = new ObjectOutputStream(fStream);
oStream.writeObject(hm);
oStream.flush();
oStream.close();
Log.v("Serialization success", "Success");
} catch (Exception e) {
Log.v("IO Exception", e.getMessage());
}
}
这是example这样做..您可以使用HashMap代替此示例中使用的GetterSetter类。
希望它有帮助..!