addPrefencesFromResource causes ClassCastException
Code:
public class Preferences extends PreferenceActivity {
public static final String PREF_AUTO_UPDATE = "PREF_AUTO_UPDATE";
public static final String PREF_MIN_MAG = "PREF_MIN_MAG";
public static final String PREF_UPDATE_FREQ = "PREF_UPDATE_FREQ";
SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
addPrefer开发者_运维知识库encesFromResource(R.xml.userprefs);
}
Every time I switch over to the preferences activity, I get a run time error that crashes my app. Down the trace I get:
Caused by: java.lang.ClassCastException: java.lang.Integer
After doing some debugging I found that commenting out the line addPreferencesFromResource
will keep the app from crashing, but (obviously) doesn't load any UI. I'm copying this example pretty much line for line out of a text book and can't figure out for the life of me what I am missing.
I was playing with this stuff and hit kind of the same thing. Turns out I was doing a putInt but then the xml file defining the preferences had a TextEditPreference hooked up with the relevant key. As far as I can tell, TextEditPreference insists on interacting with the sharedpreferences file via putString/getString (duh), and the putInt I did somewhere in playing around had stuck an element in the app-preferences.xml (/data/data/../shared_prefs/..), which kills the preference activity every time it calls addPreferencesFromResource. Not sure if that's what going on in your case, but I think folks can help once you post your userprefs and also note if you are using putInt on the TextEditPreference's key yourself in code or anything like I was (incorrectly) doing.
Check your resources type. That could be the problem.
精彩评论