Validating IP never succeeds

78 views Asked by At

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?

1

There are 1 answers

0
Guillaume Polet On BEST ANSWER

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

 IP_ADDRESS.matcher(newValue.toString()).matches()