2012-02-10 36 views
5

所以,我试图在Android上存储HashMap。我觉得最好用internal storage,但我不明白如何保存HashMap在里面然后在以后再读。有人可以解释如何正确地做到这一点吗?如何在Android上存储HashMap?

有柜台有自己的名字和价值。我想在某些活动开始时加载它们,使用它们(更改,删除,添加新的),然后保存该数据以便下次使用。现在我使用HashMap,因为它很容易删除/添加值。

HashMap<String, Integer> counters; 
+0

?或者直到你的应用程序运行。 – 2012-02-10 11:24:38

+0

请解释您对存储的确切要求。 – Raj 2012-02-10 11:24:56

+0

更多描述请。 – 2012-02-10 11:27:55

回答

12

SharedPreferences也键值对数据存储为HashMap的,所以为什么不从HashMap的所有键值,并存储到地图,因为它:

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 
    } 

代码没有编译,所以它可能有一些小错误,但应该工作。

+0

你能举一个例子说明如何使用该方法获取值吗? – Roman 2012-02-10 12:06:08

+0

不客气。 – jeet 2012-02-10 12:17:57

+1

+1似乎是存储地图的好方法,但尚未尝试。 :) – 2012-02-10 13:12:26

4

试试这个

HashMap<String, String> hashMap = new HashMap<String, String>(); 
hashMap.put("key", "value"); 
Intent intent = new Intent(this, MyOtherActivity.class); 
intent.putExtra("map", hashMap); 
startActivity(intent); 

和另一种方式是希望在一些文件作为持久性存储HERE