我有下面的示例代码。应用程序第一次安装成功。但是,它会在重新安装时引发错误。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinkedHashSet<String> planets = new LinkedHashSet<String>();
planets.add("Earth");
SharedPreferences prefs = getPreferences(0);
prefs.edit().putStringSet("planets", planets).commit();
prefs = getPreferences(0);
planets = (LinkedHashSet<String>) prefs.getStringSet("planets", new LinkedHashSet<String>());
}
}我粘贴了在重新安装下面的应用程序时产生的错误。
Caused by: java.lang.ClassCastException: java.util.HashSet cannot be cast to java.util.LinkedHashSet at com.example.test.MainActivity.onCreate(MainActivity.java:12)我想了解为什么保存的LinkedHashSet不能返回到LinkedHashSet。为什么机器人会自动转换成HashSet呢?
发布于 2013-09-13 07:05:41
@Ibungo,我认为你误解了SharedPreferences的工作。您不能要求prefs保存一个LinkedHashSet集--只能要求它保存一个普通的Set。作为回报,你可以在那之后得到一个通用的Set。不能保证它将返回与您相同的set实现。
首选项只是迭代给它们的一组项,并将它们写入应用程序的XML存储区。因此,当您请求这些项时,它正在从XML读取并创建一个新的集合-- HashSet,因为它是最常用的集合。
我可以想到,您可能想要一个LinkedHashSet的唯一原因是,您是否希望保留插入顺序。如果是这样的话,您可以尝试将集合转换为ArrayList并存储它--这里有一个示例这里。或者,您可以将数据保存到JSONArray中,并将其存储为String。
发布于 2013-09-13 06:08:07
更改代码以使用基本的HashSet
HashSet<String> planets = new LinkedHashSet<String>();
planets.add("Earth");
SharedPreferences prefs = getPreferences(0);
prefs.edit().putStringSet("planets", planets).commit();
prefs = getPreferences(0);
planets = prefs.getStringSet("planets", new LinkedHashSet<String>());附带注意:请记住,SharedPreferences.getStringSet()仅在API11+中可用。
您的Set转换为HashSet的原因可以在Android源代码中找到。
public Editor putStringSet(String key, Set<String> values) {
synchronized (this) {
mModified.put(key,
(values == null) ? null : new HashSet<String>(values));
return this;
}
}https://stackoverflow.com/questions/18779331
复制相似问题