views:

516

answers:

2

Does anyone have sample code to validate user entered text in preferences? For example, I have a EditTextPreference for user to enter an email address. I'd like to validate the format of email address entered and pop up an alert dialog if the format isn't correct. Anyone have any sample code for this? Thanks

+1  A: 

You can implement OnSharedPreferenceChangeListener to be notified when a preference value change. In that method you can validate the value:

public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    sp.registerOnSharedPreferenceChangeListener(this);
  }

  @Override
  public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
    if (key.equals("mail_preference_key")) {
        // Search for a valid mail pattern
        String pattern = "mailpattern";
        String value = sp.getString(key, null);
        if (!Pattern.matches(pattern, value)) {
            // The value is not a valid email address.
            // Do anything like advice the user or change the value
        }
    }        
  }
}
Fede
A: 

Thanks Fede for the tip.

Jay