Search code examples
javaandroidandroid-edittextstack-overflowtextwatcher

StackOverflow error in TextWatcher watcher in EditText


I'm converting my amount text from EditText to a double format and im trying to remove to "," in the EditText to execute my proper format for my computations. What's wrong with my code and having stack overflow?

// Gets the two EditText controls' Editable values

String cleanBasicTax;
if(txtBasicTax.getText().toString().contains(",")){
    cleanBasicTax=txtBasicTax.getText().toString().replace(",", "");
}
else{
    cleanBasicTax=txtBasicTax.getText().toString();
}

String cleantxtSurcharge;
if(txtSurcharge.getText().toString().contains(",")){
    cleantxtSurcharge=txtSurcharge.getText().toString().replace(",", "");
}
else{
    cleantxtSurcharge=txtSurcharge.getText().toString();
}

String cleanInterest;
if(txtInterest.getText().toString().contains(",")){
    cleanInterest=txtInterest.getText().toString().replace(",", "");
}
else{
    cleanInterest=txtInterest.getText().toString();
}

String cleanCompromise=txtCompromise.getText().toString().replace(",", "");
if(txtCompromise.getText().toString().contains(",")){
    cleanCompromise=txtCompromise.getText().toString().replace(",", "");
}
else{
    cleanCompromise=txtCompromise.getText().toString();
}           

Editable editableValueBasicTax = txtBasicTax.getText().replace(0, txtBasicTax.length(), cleanBasicTax),
    editableValueSurcharge = txtSurcharge.getText().replace(0, txtSurcharge.length(), cleantxtSurcharge),
    editableValueInterest = txtInterest.getText().replace(0, txtInterest.length(), cleanInterest),
    editableValueCompromise = txtCompromise.getText().replace(0, txtCompromise.length(), cleanCompromise);

Solution

  • Your TextWathcer changes the text that it is watching, causing another call to the watcher, causing another change to the text, ... and so on until you run out of stack space invoking methods.

    One way to fix it is to set up a boolean flag to true when you're running inside the watcher and return immediately if the flag is set to kill the recursion. In pseudocode:

    boolean mIsInWatcher = false;
    
    void onTextChanged(...) {
       if (mIsInWatcher) return;
       mIsInWatcher = true;
    
       // text modifications here
    
       mIsInWatcher = false;
    }