我在我的安卓应用程序的一些活动中有成员变量HashMap>。HashMap应该在用户首次启动应用程序后存活下来,直到应用程序被删除。我不能使用共享首选项,因为没有这样的put方法。我知道房间数据库,但我真的不想在这种情况下使用它。请告诉我有哪些选项可以保存HashMap并将其存储在内存中。
发布于 2021-03-28 03:06:34
您可以尝试将HashMap序列化为字符串。首先在您的build.gradle文件中导入该库。
implementation 'com.google.code.gson:gson:2.8.6'要序列化数据,您可以遵循以下代码:
public static String hashToString (HashMap<Integer, HashMap<String[], Integer>> hashMap) {
if (hashMap == null) return null;
Gson gson = new Gson();
//import java.lang.reflect.Type;
//import com.google.gson.reflect.TypeToken;
Type type = new TypeToken<HashMap<Integer, HashMap<String[], Integer>>(){}.getType();
return gson.toJson(hashMap, type);
}现在您可以将任何对象转换为字符串,您可以使用此方法。
要从字符串中取回对象:
public static HashMap<Integer, HashMap<String[], Integer>> stringToHash (String json) {
if (json == null) return null;
Gson gson = new Gson();
//import java.lang.reflect.Type;
//import com.google.gson.reflect.TypeToken;
Type type = new TypeToken<HashMap<Integer, HashMap<String[], Integer>>(){}.getType();
return gson.fromJson(json, type);
}发布于 2021-03-28 01:59:00
相信我用PaperDB来存储HashMap、POJO类对象、数组等等,paperDB库是最适合存储任何东西的。它只是序列化本地存储中的any对象存储。
PaperDB的Github链接:https://github.com/pilgr/Paper
在上面的链接中,你可以了解到如何使用它!
https://stackoverflow.com/questions/66834342
复制相似问题