Search code examples
androidandroid-edittextwhitespacetextchanged

app is crashing while trying to replace whitspace


To remove white space from text i have written the below code.my requirement was to remove white space coming between the text while copy-pasting the text from same EditText(type "text" copy and paste it in same EditText.the text should be "texttext" but actually it was coming like "text text"). But the problem is it is crashing when i add textChangedListener to my Edittext.

 textForm.addTextChangedListener(new TextWatcher() {

     @Override
     public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub

         String str = textForm.getText().toString().replace(" ", ""); 
         textForm.setText(str);
     }

     @Override
     public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
        int arg3) {
        // TODO Auto-generated method stub

     }

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

    }
 });

logcat error is given below

04-24 14:55:12.660: E/AndroidRuntime(20780): java.lang.StackOverflowError
04-24 14:55:12.660: E/AndroidRuntime(20780):    at android.text.TextUtils.getChars(TextUtils.java:60)

Solution

  • You've managed to create an infinite loop :)

    You change the text, which causes your onTextChanged listener to be called, where you change the text, which causes your onTextChanged listener to be called where you change the text.....

    Try this

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    
         if (textForm.getText().toString().contains(" ")){
             String str = textForm.getText().toString().replace(" ", ""); 
             textForm.setText(str);
         }
    }
    

    Or this

    @Override
    public void afterTextChanged(Editable s) {
        String replacedText = s.toString().replaceAll(" ", "");
        if (!replacedText.equals(s.toString())) {
             textForm.setText(replacedText);   
        }
    }
    

    There are probably more elegant ways to do this and getting the textview text twice is a small inefficiency, but you get the idea..