简体   繁体   English

如何在我的 Android 应用程序中保存 HashMap?

[英]How can I can save HashMap in my Android app?

I have member variable HashMap<Integer, HashMap<String[], Integer>> in some activity in my Android app.我的 Android 应用程序的某些活动中有成员变量 HashMap<Integer, HashMap<String[], Integer>>。 The HashMap supposed to survive from user launch app for the first time till the app will be deleted. HashMap 应该在用户启动应用程序后第一次存活,直到应用程序被删除。 I can't use shared preferences because there aren't such put method.我不能使用共享首选项,因为没有这样的 put 方法。 I know about room database but I don't really want to use that in this case.我知道房间数据库,但我真的不想在这种情况下使用它。 Please, tell me which options are there to save HashMap and store it in memory.请告诉我有哪些选项可以保存 HashMap 并将其存储在 memory 中。

You can try to serialize HashMap to string.您可以尝试将HashMap序列化为字符串。 Import this library in your build.gradle file first.首先将此库导入您的build.gradle文件中。

implementation 'com.google.code.gson:gson:2.8.6'

To have serialize data you can follow this code:要序列化数据,您可以遵循以下代码:

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);
}

Now you can convert any object to string you can use this method..现在您可以将任何 object 转换为字符串,您可以使用此方法..

To get back object from string:要从字符串中取回 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. 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 Link Of PaperDB: https://github.com/pilgr/Paper Github PaperDB链接: https://github.com/pilgr/Paper

In Above Link you can learn about how to use this!在上面的链接中,您可以了解如何使用它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM