Java – Prevents running twice in Android’s textwatcher

Prevents running twice in Android’s textwatcher… here is a solution to the problem.

Prevents running twice in Android’s textwatcher

I’m using Android’s TextWatcher to do this: as the user types, save what they type and change the characters in Edittext after saving. For example, I have a constant text like “hi im happy”, and everything I type in the edittext user will see that text being written (the string displays Tandemly when the user types)! I used this code in afterTextChanged:

if(s.toString().charAt(s.length()-1) != 'a'){
    save inside freaktext variable(append)
    freaktext=freaktext+s.toString().charAt(s.length()-1);

change edittext value(what user see's)
    txtfreak.setText(s.toString().substring(0, s.length()-1) + "a"); 
    txtfreak.setSelection(txtfreak.getText().length());
}else{
    freaktext=freaktext+"a";
}

I’m talking about this code, if the character you type isn’t “a”, save it in a variable named “freaktext”, then change the edittext value and put the “a” character at the end of the string in edittext. But if the user types “a”, just save it in freaktext.

bu My problem is: when the user types a non-“a” character, everything works fine and my code saves the typed character and then modifies the edittext value, but when the edittext value changes, the whole code runs again and because I changed it last time and put an “a” to it, the second part of my code (else) runs and saves the “a” again to the end of the saved string. In fact, when I type “q”, I see “qa” in the saved string!! I want the user to type “a” directly on the keyboard, save “a”, and otherwise not save. In fact, the rest of my section only runs when the user presses the “a” key directly on the keyboard. What should I do? Please help me, this code wasted 1 day of my time

Solution

Somewhere outside your function:

boolean weChangedIt = false;

Inside afterTextChanged:

if (weChangedIt) {
     weChangedIt = false;
} else {
    if(s.toString().charAt(s.length()-1) != 'a'){
        weChangedIt = true;
        freaktext=freaktext+s.toString().charAt(s.length()-1);
        txtfreak.setText(s.toString().substring(0, s.length()-1) + "a"); 
        txtfreak.setSelection(txtfreak.getText().length());
    }else{
        freaktext=freaktext+"a";
    }
}

Related Problems and Solutions