2011-04-17 107 views
1

我想迭代一個共享偏好的集合,並生成一個ArrayList的HashMaps,但有一個問題。從共享偏好Android數組

 
SharedPreferences settings = getSharedPreferences(pref, 0); 
SharedPreferences.Editor editor = settings.edit(); 
editor.putString("key1", "value1"); 
editor.putString("key2", "value2"); 

,然後我在想沿着線的東西:

 
final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>(); 
SharedPreferences settings = getSharedPreferences(pref, 0); 
Map<String, ?> items = settings.getAll(); 
for(String s : items.keySet()){ 
    HashMap<String,String> temp = new HashMap<String,String>(); 
    temp.put("key", s); 
    temp.put("value", items.get(s)); 
    LIST.add(temp); 
} 

這提供了以下錯誤:

The method put(String, String) in the type HashMap<String,String> is not applicable for the arguments (String, capture#5-of ?)

有沒有更好的方式來做到這一點?

+0

無論API級別,檢查http://sherifandroid.blogspot.com/2012/05/string-arrays-and-object-arrays-in.html – 2012-06-14 10:02:44

回答

5

哈希有正確的想法。一個對象不是一個字符串,所以.toString()是必要的。

 
final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>(); 
SharedPreferences settings = getSharedPreferences(pref, 0); 
Map<String, ?> items = settings.getAll(); 
for(String s : items.keySet()){ 
    HashMap<String,String> temp = new HashMap<String,String>(); 
    temp.put("key", s); 
    temp.put("value", items.get(s).toString()); 
    LIST.add(temp); 
} 
+1

我新的,所以我不會質疑你的答案,而是問一個問題:)使用Pair的情況如何? http://developer.android.com/reference/android/util/Pair.html – 2011-04-21 02:24:31

+0

@Bill Mote - 你的意思是代替HashMaps?我想這會起作用,但問題更多的是如何遍歷一組首選項,而不是如何操縱結果數據。我最終的目標是要有一個字符串,所以雖然Pair會持有這個對象,但我仍然需要從中得到一對字符串。 – aperture 2011-04-21 02:58:30

2

變化

HashMap<String,String> temp = new HashMap<String,String>(); 
final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>(); 

HashMap<String,?> temp = new HashMap<String,?>(); 
final ArrayList<HashMap<String,?>> LIST = new ArrayList<HashMap<String,?>>(); 

,它應該工作。你沒有放置一個字符串,而是一個對象,這會導致錯誤

+0

無法實例類型的HashMap aperture 2011-04-17 13:26:49