如何在 Android 上存储 HashMap? [英] How to store HashMap on Android?
问题描述
所以,我正在尝试在 Android 上存储 HashMap
.我觉得用内部存储比较好,但是我不明白如何保存 HashMap
在里面以后再看.有人可以解释一下如何正确地做到这一点吗?
So, I'm trying to store HashMap
on Android. I think it's better to use internal storage, but I don't understand how to save HashMap
in it and then read it later. Can someone explain how to do that properly, please?
有自己的名称和值的计数器.我想在某些活动开始时加载它们,使用它们(更改、删除、添加新的),然后保存该数据以供下次使用.现在我使用 HashMap,因为它很容易删除/添加值.
There are counters with their own names and values. I want to load them onсe when some activity was started, work with them (change, delete, add new), and then save that data to use next time. Right now I use HashMap because it's easy to delete/add values.
HashMap<String, Integer> counters;
推荐答案
SharedPreferences 也将数据存储在 key-value 对中作为 hashmap,所以为什么不从 hashmap 中获取所有 key-value 并存储到 map 中,因为它:
SharedPreferences also store data in key-value pair as hashmap, so why not get all key-values from hashmap and store into map, as it:
SharedPreferences pref= getContext().getSharedPreferences("Your_Shared_Prefs"),
Context.MODE_PRIVATE);
SharedPreferences.Editor editor= pref.edit();
for (String s : map.keySet()) {
editor.putString(s, map.get(s));
}
要获取可以使用的值:
public abstract Map<String, ?> getAll ()
http://developer.android.com/reference/android/content/SharedPreferences.html#getAll%28%29
使用:
SharedPreferences pref= getContext().getSharedPreferences("Your_Shared_Prefs"),
Context.MODE_PRIVATE);
HashMap<String, String> map= HashMap<String, String> pref.getAll();
for (String s : map.keySet()) {
String value=map.get(s);
//Use Value
}
代码未编译,因此可能有一些小错误,但应该可以工作.
Code is not compiled, so it may have some minor errors, but should work.
这篇关于如何在 Android 上存储 HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!