-1

The user enters an IP address in a EditTextPreference and I try to validate the IP with this code:

private EditTextPreference ipPref;
private Matcher matcher;
private SharedPreferences settings;
private final Pattern IP_ADDRESS
    = Pattern.compile(
    "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
    + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
    + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
    + "|[1-9][0-9]|[0-9]))");

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);

    //PREF_IP is the android:key of the EditTextPreference
    ipPref = (EditTextPreference) getPreferenceManager().findPreference("PREF_IP"); 
    settings = PreferenceManager.getDefaultSharedPreferences(this);
    matcher = IP_ADDRESS.matcher(settings.getString("PREF_IP", "0.0.0.0"));

ipPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
        public boolean onPreferenceChange(Preference preference, Object newValue) {

            try 
            {
                if(matcher.matches()){
                    Log.d("settings", "matches!");
                    return true;
                }else{
                    Log.d("settings", "doesn't match!");
                    return false;
                }
            }
            catch(Exception e)
            {
                return false;
            }
        }
    }); 
}

If I enter a valid IP address the code never sees it as valid and the log says "doesn't match!". What am I doing wrong?

glass
  • 159
  • 2
  • 12
  • You should create your matcher in the method `onPreferenceChange()` instead of creating it upfront. – Guillaume Polet Jun 20 '15 at 10:33
  • @GuillaumePolet that doesn't change anything. – glass Jun 20 '15 at 21:52
  • Yes it changes everything. But im not sure your regexp is correct – Guillaume Polet Jun 21 '15 at 10:30
  • @GuillaumePolet : I tried it and the behaviour doesn't change... that was I meant. The regex should be ok, I got it from https://stackoverflow.com/questions/3698034/validating-ip-in-android – glass Jun 21 '15 at 10:38
  • 1
    Don't know the exact internals of Android, but if you use someting like this in the onPreferenceChange() method,it should work: `IP_ADDRESS.matcher(newValue.toString()).matches()` – Guillaume Polet Jun 21 '15 at 19:25
  • That's correct! I was stupid to not take care of the Object newValue! Add your answer if you want me to accept it. Thank you! – glass Jun 22 '15 at 08:16

1 Answers1

1

Change your test in the onPreferenceChange() method, to:

 IP_ADDRESS.matcher(newValue.toString()).matches()
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117