Вопрос

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)
Это было полезно?

Решение

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..

Другие советы

this is because you are doing setText() inside onTextChanged . So when you change the text onTextChanged will be called and again inside onTextChanged you are calling setText(). So thr text changed again and onTextChanged() will be called again and this process will continue till stack overflow and result to stackOverFlow error. Hope you can understand...

user removeTextChangedListener() before setText().

Check this post for complete solution: https://stackoverflow.com/a/8600921/912851

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top