Ankur Jain Ankur Jain - 10 months ago 62
Android Question

Getting ClassCastException while running

This is my code for preference.xml

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.

Answer Source

Change this line

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


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.