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,以便在使用共享首选


- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01