Perché ricevo un ClassCastException qui?
-
27-10-2019 - |
Domanda
Sto creando un'applicazione Android e sto cercando di utilizzare un PreferenceActivity.
Sto ricevendo il java.lang.ClassCastException: java.lang.String di errore quando si arriva a questa linea return PreferenceManager.getDefaultSharedPreferences(context).getInt(USER_TERM, USER_TERM_DEF);
Ho pensato che potrebbe essere perché non sto convertendo in modo corretto dal suo valore stringa nella casella EditText al int ho bisogno, ma non riesco a capire come risolvere questo problema, o è che anche la causa? Sono sconcertato.
Ecco la mia classe di attività preferenza:
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);
}
Ed ecco il pezzo di codice in cui sto cercando di utilizzare le preferenze all'interno di un'altra classe:
public float alterForFrequency(Context keypadContext, float enteredAmount, String spinnerPosition){
int termLength = UserPrefs.getTermLength(keypadContext);
int yearLength = UserPrefs.getYearLength(keypadContext);
}
Il logcat Android completo, ho caricato qui: http://freetexthost.com/v3t4ta3wbi
Soluzione
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.