Android EditText preference validation
Asked Answered
E

1

10

I am using Edittextpreference as one of the preference in settings section. I want to validate this edittextpreference when the user enters data to it and clicks ok; before saving it in sharedpreference.

I am trying to do something like this but this saves the preference first I suppose.

editTextPreference
            .setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference,
                        Object newValue) {
                    if (((newValue.toString().length() == 15) {
                          // save preference only if length is equal to 15
                     }
              })
               });

can someone guide me how to validate edittextpreference before it is saved in sharedpreference so that I can decide if I want to save it or not.

Earn answered 24/3, 2013 at 3:59 Comment(0)
D
21

According to doc here

Called when a Preference has been changed by the user. This is called before the state of the Preference is about to be updated and before the state is persisted.

And it returns True to update the state of the Preference with the new value.

So you can do the following

      editTextPreference
            .setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference,
                        Object newValue) {
                    if (((newValue.toString().length() == 15) {
                          //
                          return true;
                     }
                     else{
                          // invalid you can show invalid message
                          return false;
                     }
              })
       });
Debatable answered 24/3, 2013 at 4:8 Comment(3)
So I'm loading preferences from xml through addPreferencesFromResource(R.xml.settings); and implementing SharedPreferences.OnSharedPreferenceChangeListener and Preference.OnPreferenceChangeListener in the PreferenceFragment instead of setting it to the EditTextPreference as you describe. The onPreferenceChange listener is never called. Only the onSharedPreferenceChanged function. Why do you think?Owades
https://mcmap.net/q/1162241/-what-is-the-difference-between-preferences-and-sharedpreferences-in-android <- might have something to do with it (difference between SharedPreferences and Preferences).Owades
If you're ok signing up for udacity this page is a really good resourceMoonier

© 2022 - 2024 — McMap. All rights reserved.