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


基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01