2

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.

Iiro Krankka
  • 4,959
  • 5
  • 38
  • 42
  • What's the output of your logcat? What error are you getting? – Kurtis Nusbaum Nov 10 '11 at 21:34
  • 1
    EditTextPreference stores its content as a String. `Float.parseFloat(String)` might be good use for you - unless you write an own `FloatPreference` which stores text input as a float. – harism Nov 10 '11 at 21:34
  • `hourly_rate = Float.parseFloat(userdata.getString("hourly_rate", "0"));` fixes this, but doesn't that kind of make `getFloat()` unnecessary? Or maybe it's for private (the user-can't-see) preferences only when you set the values in the code. – Iiro Krankka Nov 10 '11 at 21:38

2 Answers2

5

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.

harism
  • 6,011
  • 1
  • 36
  • 31
  • 1
    Why on Earth isn't it a standard feature to store primitive types as a preference? – ESP Oct 13 '15 at 13:20
2

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

Community
  • 1
  • 1
Franziskus Karsunke
  • 4,948
  • 3
  • 40
  • 54
  • Yes that was a duplicate question. Actually harism was the one who solved this for me earlier than you, but the link would've done it for me too. – Iiro Krankka Nov 10 '11 at 21:52