[英]How can I can save HashMap in my Android app?
我的 Android 应用程序的某些活动中有成员变量 HashMap<Integer, HashMap<String[], Integer>>。 HashMap 应该在用户启动应用程序后第一次存活,直到应用程序被删除。 我不能使用共享首选项,因为没有这样的 put 方法。 我知道房间数据库,但我真的不想在这种情况下使用它。 请告诉我有哪些选项可以保存 HashMap 并将其存储在 memory 中。
您可以尝试将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);
}
现在您可以将任何 object 转换为字符串,您可以使用此方法..
要从字符串中取回 object:
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 library is best for store anything believe i use paperDB to store HashMap,POJO Class Object, Array and so on... and it just serializes the any object store in local storage.
Github PaperDB链接: https://github.com/pilgr/Paper
在上面的链接中,您可以了解如何使用它!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.