EditText validation with TextWatcher

Tivie picture Tivie · Nov 22, 2010 · Viewed 15.6k times · Source

I have a Dialog with a EditText and a button. This EditText will name the database table I will create so its of the utmost importance it is validated. So i would like to pose 2 questions:

1) This is quite simple, but i couldn't fin it anywhere: what characters can a database table name accept? Can it accept numbers? And can a number be the first character?

2) I've managed to validate the EditText using TextWtacher. Here's the code:

et_name.addTextChangedListener(new TextWatcher() {

public void afterTextChanged(Editable s) {

    String filtered_str = s.toString();

        if (filtered_str.matches(".*[^a-z^0-9].*")) {

        filtered_str = filtered_str.replaceAll("[^a-z^0-9]", "");

        s.clear();

        // s.insert(0, filtered_str);

        Toast.makeText(context,
            "Only lowercase letters and numbers are allowed!",
            Toast.LENGTH_SHORT).show();

    }

}

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    public void onTextChanged(CharSequence s, int start, int before, int count) {}
});

Currently, if the user inserts any character other than lowercase letters and numbers, the textbox is cleared. If I uncomment s.insert(0, filtered_str); in order to to replace the EditText with the filtered string, my app hangs. And guess what I find in the debug?

ERROR/AndroidRuntime(2454): java.lang.StackOverflowError =D

The question is... how can I replace the s text?

-> s.replace(0, s.toString().length(), filtered_str); (remove s.clear, of course) doesn't seem to work either.

Answer

El David picture El David · Dec 26, 2012
private TextWatcher listenerTextChangedFiltro = new TextWatcher() {
        public void afterTextChanged(Editable editable) {

                final String textoFiltrado = StaticString.filterTextCustom(String.valueOf(editable.toString().toLowerCase()));
                if (!textoFiltrado.equals(editable.toString().toLowerCase())) {
                    editable.clear();
                    editable.append(textoFiltrado);
                }
         }
};