Android MultiSelectListPreference, java.lang.String cannot be cast to java.util.Set

0

本文作者:xjtudll  发布于:2017-6-26  分类:技术心得  点击:


问题及现象:

尝试添加一个 MultiSelectListPreference到设置界面,MultiSelectListPreference基本代码如下:

<MultiSelectListPreference

android:title="@string/title"

android:summary="@string/message"

android:key="pref_foobar"

android:defaultValue="@array/empty_array"

android:entries="@array/fooArray"

android:entryValues="@array/fooValues" />


array如下:

<resources>

<string-array name="fooArray">

<item>Foo</item>

<item>Bar</item>

</string-array>

<string-array name="fooValues">

<item>foo_value</item>

<item>bar_value</item>

</string-array>

<string-array name="empty_array"/>

</resources>


编译后警告如下:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myproject/.SettingsActivity}: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Set

以下是Activity的代码:

public class SettingsActivity extends Activity {
private static final String TAG_SETTINGS_FRAGMENT = "SETTINGS_FRAGMENT";
@Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

if (savedInstanceState == null) {            getFragmentManager().beginTransaction() .replace(android.R.id.content, new PreferenceFragment(), TAG_SETTINGS_FRAGMENT).commit(); } }

public static class PreferenceFragment extends android.preference.PreferenceFragment{

public PreferenceFragment() { //required }

@Override public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);            addPreferencesFromResource(R.xml.preferences); } }}

 


 

原因:

某个Key的属性之前是String,后来改成了Set,且在调试的过程中曾经存储过数据,所以才会冲突。

It feels like you already have a plain String preference under this key on your device or emulator. Try completely uninstalling and reinstalling the app, or using "Clear Data" for the app in its screen in Settings, to wipe out your existing SharedPreferences.


解决办法:

1、清除该APP数据;

2、卸载APP再重装;

 

参考资料:http://stackoverflow.com/questions/26179178/android-multiselectlistpreference-java-lang-string-cannot-be-cast-to-java-util

0 Comments

Write a comment ?