0

i wanted to validate a EditText and see if all of the letters are alphabet. it should be able to handle multiple EditText. i need a way to prevent user from entering anything other then alphabet.

        userTextInput=(EditText)findViewById(R.id.textInput);
    userTextInput.addTextChangedListener(this);

    public void afterTextChanged(Editable edit) {
    String textFromEditView = edit.toString();
            //first method
    ArrayList[] ArrayList;
    //ArrayList [] = new ArrayList;
    for(int i=0; i<=textFromEditView.length(); i++)
    {
        if(textFromEditView[i].isLetter() == false)
        {
            edit.replace(0, edit.length(), "only alphabets");
        }
    }
            //second method
    try
    {
        boolean isOnlyAlphabet = textFromEditView.matches("/^[a-z]+$/i");
        if(isOnlyAlphabet == false)
        {
            edit.replace(0, edit.length(), "only alphabets");
        }
    }
    catch(NumberFormatException e){}


}

for my second method the moment i enter anything, number or alphabet, my app crash. i have test my first method because it has the error textFromEditView must be an array type bue is resolved as string. can you help me to improve my code.

Myst
  • 177
  • 1
  • 6
  • 24

3 Answers3

2

I think you'd do better using InputFilter:

InputFilter filter = new InputFilter() { 
        public CharSequence filter(CharSequence src, int start, int end,
                                                   Spanned d, int dstart, int dend) { 
                for (int i = start; i < end; i++) { 
                        if (!Character.isLetter(src.charAt(i))) { 
                                return src.subSequence(start, i-1); 
                        } 
                } 
                return null; 
        } 
}; 

edit.setFilters(new InputFilter[]{filter});

Code modified from: How do I use InputFilter to limit characters in an EditText in Android?

Community
  • 1
  • 1
Kuba Spatny
  • 26,618
  • 9
  • 40
  • 63
  • 1
    i found a good solution use. android:digits="qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM" /> in the xml. so far no problems. is the same link you gave me. thanks for the help! – Myst Jan 28 '14 at 16:56
  • Saw that too, but never tried it. If you're more satisfied with that, then don't hesitate to post it as an answer! – Kuba Spatny Jan 28 '14 at 16:58
2
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

How to create EditText accepts Alphabets only in android?

Community
  • 1
  • 1
Khang .NT
  • 1,504
  • 6
  • 24
  • 46
  • Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – galath Jul 27 '15 at 12:48
0

You can set the inputType of the EditText. More Information here and here.

Giacomoni
  • 1,468
  • 13
  • 18