Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences getFloat returns ClassCastException and force closes

I want to get a float from the preferences. This works fine when the user doesn't enter anything, but when entering 8.23 to the box and saving it, the app crashes on the next start.

MainActivity.java:

float hourly_rate;
SharedPreferences userdata;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    userdata = PreferenceManager.getDefaultSharedPreferences(this);
    hourly_rate = userdata.getFloat("hourly_rate", 0.0f);
}

Preferences.xml:

<PreferenceCategory
    android:title="@string/general_preferences_title">
    <EditTextPreference
        android:inputType="numberDecimal"
        android:key="hourly_rate"
        android:title="@string/hourly_rate_title"
        android:summary="@string/hourly_rate_summary" />
</PreferenceCategory>

When I remove the getFloat line, the app doesn't force close.

like image 648
Iiro Krankka Avatar asked Aug 02 '26 10:08

Iiro Krankka


2 Answers

EditTextPreference stores its content as a String. Float.parseFloat(String) might be good use for you - among with preferences.getString(..) - unless you write an own FloatPreference which stores text input as a float.

like image 106
harism Avatar answered Aug 04 '26 00:08

harism


This question is maybe the same: How does one declare the type of an Android preference?. It might solve your problem.

like image 20
Franziskus Karsunke Avatar answered Aug 03 '26 22:08

Franziskus Karsunke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!