1

I have a customized EditText class, whats is happening is that there is a validation already for the field, checking it's length and doing trim.

But, the app is crashing because it is possible to click in the field and insert data after 1 space.

How can I validate when clicking, that user can not write his data? If he/she writes data with one space, the app crashes and I receive the following exception.

java.lang.IllegalArgumentException: Start position must be less than the actual text length

Thanks in advance.

4 Answers4

1

Either you can trim but remember this wont restrict to enter white spaces by user, If you want to restrict white spaces then you need to add filter for your edit text. Adding filter let you restrict what ever character you want to avoid.

P.S - Check for adding filter on given link How do I use InputFilter to limit characters in an EditText in Android?

Community
  • 1
  • 1
Daud Arfin
  • 2,499
  • 1
  • 18
  • 37
1

add "addTextChangedListener" to your EditText and then onTextChanged you can check for your validation. For example,

txtEdit.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            String str = s.toString();
            if(str.length() > 0 && str.startsWith(" ")){
                Log.v("","Cannot begin with space");
                txtEdit.setText("");
            }else{
                Log.v("","Doesn't contain space, good to go!");
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
Atul O Holic
  • 6,692
  • 4
  • 39
  • 74
0

trim the string that you get from edit text.

   String str=edtext.getText().toString().trim();


if(str!=null && !str.equalsIgnoreCase("")))
{
//perform your operations. 
}
else
{
//give error message.
}
Harshal Benake
  • 2,391
  • 1
  • 23
  • 40
  • Forgot to say but I'm already doing this validation. final int number = Integer.parseInt(formNumber.getTextField() .getText().toString().trim()); – Leonardo Leonardo Feb 03 '14 at 13:07
0

Get the edit text first by this way:

EditText name=(EditText) findViewById(R.id.txt);
String txtEdit=txt.getEditableText().toString();

then check the text length validation by:

if(txtEdit.length() == 0)  {

               //your code for what you want to do.

}              
Umit Kaya
  • 5,771
  • 3
  • 38
  • 52