我正在尝试遍历共享首选项的集合,并生成 HashMap 的 ArrayList,但遇到了问题。
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 ?)
有更好的方法吗?
最佳答案
Hache 的想法是正确的。对象不是字符串,因此 .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); }
关于来自共享首选项的android数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5693646/