如何存储哈希映射到Android,这样它会被重用使用共享preferences重新启动应用程序时?它会、重新启动、应用程序、Android

2023-09-04 13:32:10 作者:我不发光谁发

我想HashMap来存储我的Andr​​oid应用程序,当重新启动时,它显示的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>(); 

是我的HashMap和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和存储在preferences生成的字符串。然后,当应用程序重新启动获得preferences字符串和反序列化。

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.

编辑:

要做到这一点,您可以使用谷歌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();