我有成员变量HashMap<Integer,HashMap<String[],Integer>gt;在我的Android应用程序中的一些活动中。HashMap应该是第一次从用户启动应用程序中幸存下来,直到该应用程序被删除。我不能使用共享偏好,因为没有这样的put方法。我知道房间数据库,但我真的不想在这种情况下使用它。请告诉我有哪些选项可以保存HashMap并将其存储在内存中。
您可以尝试将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);
}
PaperDB库最适合存储任何东西。相信我使用PaperDB来存储HashMap、POJO类对象、数组等……它只是串行化本地存储中的任何对象存储。
PaperDB的Github链接:https://github.com/pilgr/Paper
在上面的链接中,你可以了解如何使用它!