PreferenceActivity: save value as integer
Solution 1
You could extend EditTextPreference:
public class IntEditTextPreference extends EditTextPreference {
public IntEditTextPreference(Context context) {
super(context);
}
public IntEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public IntEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected String getPersistedString(String defaultReturnValue) {
return String.valueOf(getPersistedInt(-1));
}
@Override
protected boolean persistString(String value) {
return persistInt(Integer.valueOf(value));
}
}
It would be better to overwrite onSetInitialValue() and setText() methods, but then you would have to copy some code from a base class. Above solution is simplier, but it's quite tricky - "string" methods do something with ints. Try to not extend this class further ;-)
You could use it from XML by:
<package.name.IntEditTextPreference
android:key="SomeKey"
android:title="@string/some_title"
android:summary="..."
android:numeric="integer"
android:maxLength="2"
/>
Solution 2
Even if you set android:numeric="integer" it'll be text preference - as its name suggest. You could easily convert string value to int using Integer.valueOf(). Also you could overwrite PreferenceActivity to do conversion automatically on exit.
I think the best solution is to write simple method to get this value from preferences. Something like:
public static int getSomePref(Context context) {
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(context);
String value = prefs.getString("SomeKey", null);
return value == null ? -1 : Integer.valueOf(value);
}
Then you could very easily use it from your code.
Solution 3
Even though an Answer has been parked accepted I would like to share one more shorter way to achieve this :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int value = Integer.parseInt(preferences.getString("SomeKey", "-1"));
Since you have already set that only numbers can be entered this won't through any exception. yet to complete my answer :
<EditTextPref
android:key="SomeKey"
android:title="@string/some_title"
android:summary="..."
android:numeric="integer"
android:maxLength="2" />
Laimoncijus
Updated on February 14, 2021Comments
-
Laimoncijus over 3 years
Using a simple
EditTextPreference
in my preferences activity:<EditTextPreference android:key="SomeKey" android:title="@string/some_title" android:summary="..." android:numeric="integer" android:maxLength="2" />
Is there a way that this configuration value would be saved as integer? Seems now it just allows to enter numbers, but the value is still saved as string:
Calling:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); int value = preferences.getInt("SomeKey", -1);
throws me
java.lang.ClassCastException: java.lang.String
, and:SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String value = preferences.getString("SomeKey", "-1");
retrieves the value successfully.
How to make
PreferenceActivity
to save value as integer by default? -
Laimoncijus almost 14 yearsWhere can I override this? By default
PreferenceActivity
does the saving automatically, should I override some method for getting the value or do all saving myself instead? -
broot almost 14 yearsOk, changing type of preference isn't good, cause you may get ClassCastException problems. I have updated my answer.
-
Laimoncijus almost 14 yearsYes, I thought about wrapper myself, but somewhat I still don't like this solution...
SharedPreferences
hasgetInt
method already, so still hoping somehow to find a way how to tellPreferenceActivity
to save the value as int - all functionality is there... just doesn't work as whished... -
broot almost 14 yearsYou could always wrote your own Preference class.
-
Admin over 12 years@Brutall, I'd like to say thanks to you by improving the code. But someone said to me that the new code is... too long, and he rejected it. Oh, but what do people do if the old code is bad, and need to be replaced, but they don't do it because the new one is... long? Even if it is better. Oh my, that's GREAT! This is place for programmers? I have some open source projects, and I'm opening for any changes to my code. How shame to him! Anyway, thank you so much, Brutall.
-
Admin over 12 yearsBtw, all I do is: set input type to number; add a
TextWatcher
, to make sure the text user enters is not empty, and default value is0
. -
ibaguio over 11 yearsim getting a runtime error on
return String.valueOf(getPersistedInt(-1));
, cannot start activity due to that line -
Michael over 9 years@user942821 but is there no preference that defaults to type int? This is crazy that it isn't just there, that all this extra code is needed. Why isn't there just an "EditIntPreference" tag by default?
-
Michael over 9 years@user942821 and it's doubly annoying because I just want to expose some internal integer preferences for debugging, they aren't even normally something the user should edit!
-
Farid almost 7 yearsWell, not working. gives error in line
return String.valueOf(getPersistedInt(-1));
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
-
Flávio Etrusco almost 6 yearsIf you want the value to be persisted as "int", i.e. you want to use preferences.getInt() to load the preference, you need to use the accepted answer.
-
GSD.Aaz over 4 yearsThe following functions support defaultValue ;-)
@Override protected String getPersistedString(String defaultReturnValue) { return String.valueOf(getPersistedInt(defaultReturnValue == null ? -1 : Integer.valueOf(defaultReturnValue))); } @Override protected boolean persistString(String value) { return persistInt(value != null ? Integer.valueOf(value) : -1); }
-
akelec over 4 years2019 UPDATE:
android:numeric
is deprecated, you should useandroid:inputType="number"
. -
akelec over 4 years2019 UPDATE:
android:numeric
is now deprecated, you should use insteadandroid:inputType="number"
. -
Fran Marzoa almost 4 yearsThe OP has asked how to SAVE the value as an Integer. This answer does NOT address that question, it merely provides a workaround to get an Integer back while still saving a STRING.
-
Fran Marzoa almost 4 yearsI'd suggest to replace that "-1" there with "Integer.valueOf(defaultReturnValue)" so it uses the actual default value defined in the preference XML file
-
Iogui over 3 years@akelec inputType does nothing since EditTextPreference is not an EditText itself. The EditText that really matters is in a dialog so in order to achieve the desired effect one have to override the
onBindEditText
method and set the input type from there:editText.setInputType(InputType.TYPE_CLASS_NUMBER);