29

I have a preferences.xml that looks like this:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android">
 <EditTextPreference
  android:name="Sample"
  android:enabled="true"
  android:persistent="true"
  android:summary="Sample"
  android:defaultValue="3.0"
  android:title="Sample"
  android:key="sample" />
</PreferenceScreen>

When I do sp.getString("sample", "3.0"), it works fine and returns a string, but it shouldn't be a string, it should be a float. Running sp.getFloat("sample", 3.0f) throws a ClassCastException because it is a string.

What should I put in the XML so that the preference is stored as a float?

David R.
  • 493
  • 1
  • 6
  • 10

3 Answers3

44

In your preferences xml you can add an option android:numeric with the value "integer". This way the user should only be able to enter a valid integer value.

When loading the setting you should try to parse it to a number yourself (as all values are stored as Strings (@mbaird below)):

try {
  float val = Float.parseFloat(sp.getString("sample", "3.0f"));
} catch (NumberFormatException e) {
  // "sample" was not an integer value
  // You should probably start settings again
}
MrSnowflake
  • 4,724
  • 3
  • 29
  • 32
  • 3
    Seems to work, even though Eclipse doesn't offer Intellisense for the "android:numeric"-part ... therefore I would've never thought of that, thanks! – Select0r Feb 15 '11 at 22:49
  • this works well. I'm not relying on user input, but a list that refers to string floats. Very easy to do and easy to handle the catch. – Nlinscott Dec 12 '14 at 05:03
9

If you are using the built in preferences screen API instead of writing your own preferences Dialogs or Activities, then you are going to be a bit limited in some respects. For example EditTextPreference will always store the value as a String.

From the API Doc:

This preference will store a string into the SharedPreferences.

I note that there doesn't appear to be any way for you to restrict the user to just typing in a valid floating point number in your text field. What would you do if they typed in "abc"?

cuihtlauac
  • 1,808
  • 2
  • 20
  • 39
Mark B
  • 183,023
  • 24
  • 297
  • 295
  • "there doesn't appear to be any way for you to restrict the user to just typing in a valid floating point number in your text field" Actually there is, at least as of today. android:numeric="decimal" is the better approach, but there are others. – Fran Marzoa Jun 26 '19 at 13:17
4

As mbaird pointed out you can't force to store as Float.

But you can change the EditTextPreference to a plain Preference view, and implement the click event for it. This way you will be able to create and show your own Dialog, for edit the value, and thus you can restrict the format and save as Float to the preference file.

Pentium10
  • 204,586
  • 122
  • 423
  • 502