我正在尝试迭代共享首选项的集合,并生成HashMaps的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 ?)
有更好的方法吗?
答案 0 :(得分:5)
哈希有正确的想法。 Object不是String,所以.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 :(得分: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,?>>();
它应该有效。你没有放一个字符串,而是一个导致错误的对象