Android Preferences error, "String cannot be cast to int"

android, integer, java, sharedpreferences, string

Solution

Your Preferences in XML, even if you set `android:inputType="number"` are still stored as a String

You have 2 choices:

1) the 'not-so-nice': `Integer.parseInt( preferences.getString("defaultTip", "15"));`

2) Using your own type of Integer Preference. More complicated to set in first place but really better (similar question here: https://stackoverflow.com/a/3755608/327402)

Problem

I'm trying to setup a preferences activity but my app keeps crashing and I get the following logcat: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.appthing.myapp/com.appthing.myapp.Main}: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer 07-24 16:37:59.556: E/AndroidRuntime(17384): at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:240) In my `Main` activity I have the following code inside the `onResume()` method: ``` SeekBar tipSeekBar = (SeekBar) findViewById(R.id.tipSeekBar); SeekBar splitSeekBar = (SeekBar) findViewById(R.id.splitSeekBar); SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(this); tipSeekBar.setProgress(preferences.getInt("defaultTip", 15)); splitSeekBar.setProgress(preferences.getInt("defaultSplit", 1)); tipSeekBar.setMax(preferences.getInt("maxTip", 25)); splitSeekBar.setMax(preferences.getInt("maxSplit", 10)); ``` Here is what I have in the Preference class (as requested): ``` addPreferencesFromResource(R.layout.preferences); // I was told in tutorials this is all I need in the oncreate method ``` I don't understand why its saying something about a string. All my values are integers and I am using `android:inputType="number"` to make sure only an int can be entered. I have also tried uninstalling and re-installing the app to clear the cache and nothing works. RESOLVED: "Your Preferences in XML, even if you set android:inputType="number" are still stored as a String" (by Waza_Be). All I had to do is do `Integer.parseInt()` to grab the correct value.

Original source

Related problems