Question

I'm creating an android application and i'm trying to use a PreferenceActivity.

I'm getting the java.lang.ClassCastException: java.lang.String error when it gets to this line return PreferenceManager.getDefaultSharedPreferences(context).getInt(USER_TERM, USER_TERM_DEF);

I thought it might be because I'm not converting it properly from it's string value in the EditText box to the int I need but I can't figure out how to fix this, or is that even the cause? I'm flummoxed.

Here's my preference activity class:

public class UserPrefs extends PreferenceActivity {
//option names and default vals
private static final String USER_TERM = "term_length";
private static final String USER_YEAR = "year_length";
private static final int USER_TERM_DEF = 12;
private static final int USER_YEAR_DEF = 34;

@Override 
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences); 
}

public static int getTermLength(Context context){
    try{
    return PreferenceManager.getDefaultSharedPreferences(context).getInt(USER_TERM, USER_TERM_DEF);
    }catch (ClassCastException e){Log.v("getTermLength", "error::: " + e); }
    //return 1;//temporary, needed to catch the error and couldn't without adding a return outside the block.//
}
public static int getYearLength(Context context){
    return PreferenceManager.getDefaultSharedPreferences(context).getInt(USER_YEAR, USER_YEAR_DEF);
}

And here's the bit of code where I'm trying to use the the preferences inside another class:

public float alterForFrequency(Context keypadContext, float enteredAmount, String spinnerPosition){

    int termLength = UserPrefs.getTermLength(keypadContext);
    int yearLength = UserPrefs.getYearLength(keypadContext);
}

The complete android logcat, i've uploaded here: http://freetexthost.com/v3t4ta3wbi

Was it helpful?

Solution

You have a preference that is stored as a String and you are trying to read it in as an int, hence the ClassCastException.

If you're happy to leave the preference stored as a string, you could just use getString and pass that value to Integer.parseInt() to get an int.

Otherwise, you need to make sure the value gets written to the preferences as an int.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top