java 如何将 Hashmap 存储到 android 以便在使用共享首选项重新启动应用程序时可以重用它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11931753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Store Hashmap to android so that it will be reuse when application restart using shared preferences?
提问by user1594950
I want to store hashmap to my android application that when restart ,it shows last saved values of hashmap.
我想将 hashmap 存储到我的 android 应用程序中,当重新启动时,它会显示最后保存的 hashmap 值。
HashMap<Integer,String> HtKpi=new HashMap<Integer,String>();
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).
是我的哈希图,其中动态存储了 44 个值。效果很好!!!现在,我想存储它以备将来使用(应用程序重启或重用)。
回答by kgautron
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.
您可以将其序列化为 json 并将结果字符串存储在首选项中。然后当应用程序重新启动时,从首选项中获取字符串并将其反序列化。
EDIT :
编辑 :
To do so you can use Google Gsonfor example.
为此,您可以使用例如Google Gson。
You will need to wrap your map in a class:
您需要将地图包装在一个类中:
public class MapWrapper {
private HashMap<Integer, String> myMap;
// getter and setter for 'myMap'
}
To store the map:
存储地图:
Gson gson = new Gson();
MapWrapper wrapper = new MapWrapper();
wrapper.setMyMap(HtKpi);
String serializedMap = gson.toJson(wrapper);
// add 'serializedMap' to preferences
To retrieve the map:
要检索地图:
String wrapperStr = preferences.getString(yourKey);
MapWrapper wrapper = gson.fromJson(wrapperStr, MapWrapper.class);
HashMap<Integer, String> HtKpi = wrapper.getMyMap();
回答by JJ_Coder4Hire
using Raghav's I created a complete working example:
使用 Raghav's 我创建了一个完整的工作示例:
public class AppCache {
public static HashMap<String, String> hashMap = null;
/* REPOSITORY NAME */
public static final String REPOSITORY_NAME = "HMIAndroid_System_Settings";
/* SETTINGS */
public static final String SETTING_PLANNED = "DATA_PLANNED";
public static final String SETTING_ACTUAL = "DATA_ACTUAL";
public static final String SETTING_ETA = "DATA_ETA";
public static final String SETTING_OR = "DATA_OR";
public static final String SETTING_LINEID = "LINEID";
public static final String SETTING_SERVERIP = "SERVERIP";
public static void LoadSettings(Context context) {
SharedPreferences pref = context.getSharedPreferences(REPOSITORY_NAME, Context.MODE_PRIVATE);
hashMap = (HashMap<String, String>) pref.getAll();
if(hashMap == null) {
hashMap = new HashMap<String, String>();
}
}
public static void SaveSettings(Context context) {
if(hashMap == null) {
hashMap = new HashMap<String, String>();
}
//persist
SharedPreferences pref = context.getSharedPreferences(REPOSITORY_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
for (String s : hashMap.keySet()) {
editor.putString(s, hashMap.get(s));
}
editor.commit();
}
}
Then in your onCreate load it:
然后在你的 onCreate 加载它:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//load settings
AppCache.LoadSettings(getApplicationContext());
Log.d("onCreate","My LineID=" + AppCache.hashMap.get(AppCache.SETTING_LINEID));
Log.d("onCreate","Dest ServerIP=" + AppCache.hashMap.get(AppCache.SETTING_SERVERIP));
}
at any time anywhere in your app update settings:
随时随地在您的应用更新设置中:
AppCache.hashMap.put(AppCache.SETTING_LINEID, "1");
AppCache.hashMap.put(AppCache.SETTING_SERVERIP, "192.168.1.10");
in your onDestroy save settings to cache:
在您的 onDestroy 保存设置以缓存:
@Override
protected void onDestroy() {
//save settings
AppCache.SaveSettings(getApplicationContext());
}
回答by Raghav Sood
Serialize it and save it in shared preferences or in a file. Whether you can do this, of course, depends on the data types being mapped from and to. (This won't work, for instance, if you try to serialize a View.)
将其序列化并将其保存在共享首选项或文件中。当然,您是否可以执行此操作取决于被映射的数据类型和映射到的数据类型。(例如,如果您尝试序列化视图,这将不起作用。)
Example:
例子:
//persist
HashMap<String, Integer> counters; //the hashmap you want to save
SharedPreferences pref = getContext().getSharedPreferences("Your_Shared_Prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
for (String s : counters.keySet()) {
editor.putInteger(s, counters.get(s));
}
editor.commit();
//load
SharedPreferences pref = getContext().getSharedPreferences("Your_Shared_Prefs", Context.MODE_PRIVATE);
HashMap<String, Integer> map= (HashMap<String, Integer>) pref.getAll();
for (String s : map.keySet()) {
Integer value=map.get(s);
//Use Value
}
回答by Rakesh Gondaliya
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
You can store it here.... This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state.
你可以把它存储在这里....这个方法在一个活动可能被杀死之前被调用,这样当它在未来某个时间回来时它可以恢复它的状态。
And then you can retireve it back from here,,,
然后你可以从这里收回它,,,
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
}
This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState...
当活动从先前保存的状态重新初始化时,在 onStart() 之后调用此方法,此处在 savedInstanceState 中给出...
I think that this will help
我认为这会有所帮助
回答by Suresh
I have a solution. Same thing i had done in my application where i wanted to store the name of states as key and state abbreviation as value. For that declared an string array in "res/values/string.xml". Here is the code used to declare an array :
我有一个解决方案。我在我的应用程序中做过同样的事情,我想将状态名称存储为键,将状态缩写存储为值。对于在“res/values/string.xml”中声明的字符串数组。这是用于声明数组的代码:
<string-array name="array_string">
<item>yourKey1;yourValue1</item>
<item>yourKey2;yourValue2</item>
<item>yourKey3;yourValue3</item>
</string-array>
And after this, where you want to instantiate your hashmap, do this :
在此之后,您要在其中实例化您的哈希图,请执行以下操作:
HashMap<String, String> map = new HashMap<String, String>();
Resources res = getResources();
String[] stringArray = res.getStringArray(R.array.array_string);
//R.array.array_string is the name of your array declared in string.xml
if(stringArray == null || stringArray.length == 0) return;
for(String string : stringArray) {
String[] splittedString = string.split(";");
if(splittedString.length > 0) {
String key = splittedString[0];
String value = splittedString[1];
map.put(key, value);
}
}
Now you have your HaspMap instance ready for use. This is simple way of doing this which i prefer.
现在您已准备好使用您的 HaspMap 实例。这是我更喜欢的简单方法。