How to Store Hashmap to android so that it will be reuse when application restart using shared preferences?(如何将 Hashmap 存储到 android,以便在使用共享首选项重新启动应用程序时重用它?)
问题描述
我想将 hashmap 存储到我的 android 应用程序中,当重新启动时,它会显示最后保存的 hashmap 值.
I want to store hashmap to my android application that when restart ,it shows last saved values of hashmap.
HashMap<Integer,String> HtKpi=new HashMap<Integer,String>();
是我的哈希图,其中动态存储了 44 个值.这很好用!!!现在,我想存储它以备将来使用(应用程序重新启动或重用).
is my hashmap and 44 values are stored in it dynamically. That works fine!!! now,I want to store it for future use(Application restart or reuse).
推荐答案
您可以将其序列化为 json 并将结果字符串存储在首选项中.然后当应用程序重新启动时,从首选项中获取字符串并对其进行反序列化.
You could serialize it to json and store the resulting string in the preferences. Then when application restarts get the string from preferences and deserialize it.
为此,您可以使用 Google Gson 例如.
To do so you can use Google Gson for example.
您需要将地图包装在一个类中:
You will need to wrap your map in a class:
public class MapWrapper {
private HashMap<Integer, String> myMap;
// getter and setter for 'myMap'
}
要存储地图:
Gson gson = new Gson();
MapWrapper wrapper = new MapWrapper();
wrapper.setMyMap(HtKpi);
String serializedMap = gson.toJson(wrapper);
// add 'serializedMap' to preferences
要检索地图:
String wrapperStr = preferences.getString(yourKey);
MapWrapper wrapper = gson.fromJson(wrapperStr, MapWrapper.class);
HashMap<Integer, String> HtKpi = wrapper.getMyMap();
这篇关于如何将 Hashmap 存储到 android,以便在使用共享首选项重新启动应用程序时重用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 Hashmap 存储到 android,以便在使用共享首选


基础教程推荐
- Java Swing计时器未清除 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01