【问题标题】:android array from shared preferences来自共享首选项的android数组
【发布时间】:2011-08-07 07:26:42
【问题描述】:

我正在尝试迭代一组共享首选项,并生成一个 HashMap 的 ArrayList,但遇到了问题。

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

然后我在想一些事情:

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

这会产生以下错误:

HashMap 类型中的 put(String, String) 方法不适用于参数 (String, capture#5-of ?)

有没有更好的方法来做到这一点?

【问题讨论】:

标签: android android-preferences


【解决方案1】:

Hache 的想法是正确的。对象不是字符串,所以 .toString() 是必要的。

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

【讨论】:

  • 我是新手,所以我不是在质疑你的答案,而是在问一个问题:) 使用 Pair 怎么样? developer.android.com/reference/android/util/Pair.html
  • @Bill Mote - 你的意思是代替 HashMaps?我想这会起作用,但问题更多的是如何遍历一组偏好,而不是如何操作结果数据。我的最终目标是拥有一个字符串,因此虽然 Pair 会持有该对象,但我仍然需要从中获取一对字符串。
【解决方案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,?>>();

它应该可以工作。你不是在放一个字符串而是一个对象,这会导致错误

【讨论】:

  • 无法实例化类型 HashMap
猜你喜欢
  • 2013-07-23
  • 2011-10-05
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多