如何将 Hashmap 存储到 android,以便在使用共享首选项重新启动应用程序时重用它? [英] How to Store Hashmap to android so that it will be reuse when application restart using shared preferences?

查看:24
本文介绍了如何将 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,以便在使用共享首选项重新启动应用程序时重用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆