I have a preferences.xml
which contains the following definition:
<ListPreference
android:title="@string/LimitSetting"
android:summary="@string/LimitSettingText"
android:key="limitSetting"
android:defaultValue="10"
android:entries="@array/limitArray"
android:entryValues="@array/limitValues" />
and with values defined as follows:
<string-array name="limitArray">
<item>1 %</item>
<item>3 %</item>
<item>5 %</item>
<item>10 %</item>
<item>20 %</item>
</string-array>
<string-array name="limitValues">
<item>1</item>
<item>3</item>
<item>5</item>
<item>10</item>
<item>20</item>
</string-array>
which is being called in an activity as follows:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int offsetProgressInitial = sharedPref.getInt("limitSetting", 10);
So far so good, but when the code gets actually called I get this error:
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:239)
at com.test.app.NewEntryActivity.onCreate(NewEntryActivity.java:144)
at android.app.Activity.performCreate(Activity.java:5977)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
This error does not make any sense to me. The list only contain values that can be converted into an int, and the default values given in the xml file and in the code also represents just a number. So why do I get this error, and how to fix it?
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"));
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With