Search code examples
javaandroidclasscastexceptionandroid-sharedpreferences

Getting ClassCastException while running


This is my code for preference.xml

<EditTextPreference
        android:defaultValue="3"
        android:key="number"
        android:numeric="integer"
        android:summary="Enter how many Days older files"
        android:title="Set Days" />

and when i am trying to get its value with sharedpreference as below

int fileolderthan = sharedPreferences.getInt("number",7);

Getting error on running code java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer.

How to fix it, any tip please.


Solution

  • Change this line

    int fileolderthan = sharedPreferences.getInt("number",7);
    

    with

    int fileolderthan = Integer.valueOf(sharedPreferences.getString("number","7"));
    

    EditTextPreference saves value as string even if you set android:numeric="integer". So you first retrieve the string, then convert it into integer.