I have a preferences.xml
which contains the following definition:
First let's have a look at SharedPreferences.getInt() method.
public abstract int getInt (String key, int defValue)
Parameters
Returns : Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not an int.
So in your case, all the entry values have been defined as a string array. Therefore the class cast exception will be thrown.
You can simply solve this problem by modifying your code as follows.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int offsetProgressInitial = Integer.parseInt(sharedPref.getString("limitSetting", "10"));
If you look at what getInt()
does internally you will see the problem:
Integer v = (Integer)mMap.get(key);
Your key "limitSetting" is returning a String
which cannot be cast to an Integer.
You can parse it yourself however:
int offsetProgressInitial = Integer.parseInt(sharedPref.getString("limitSetting", "10"));
The problem is that if putInt
was never called then getInt
will return a null value, even if you set a default integer value.
This seems to be a bug that was never fixed. So the solution is to call the putInt
before calling getInt
.