different regex behaviour on different devices

100 views Asked by At

I'm having a strange bug when I try to check an EditText (I want the text to be an IBAN, like FR76 2894 2894 2894 289), so I'm doing this (overriding my edit text's onTextChanged):

// format with IBAN regex
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
    editText.setText(editText.getText().toString().replaceAll(" ", "")
            .toUpperCase().replaceAll("[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}", "$0 ")); 
}

I'm doing a comparison with two different Android phones: an Asus Zenfone and an Honor 5C.

Both devices have the same bevahiour on first char typed (valid only if it's a letter). But then, when I type a second letter (text should be FR after this):

Honor 5C: (expected behaviour)

enter image description here

Asus Zenfone: (wrong behaviour)

enter image description here

Any idea? Thanks for your help.

1

There are 1 answers

0
aveuiller On

As you can see in the documentation, it seems like a bad idea to call setText from onTextChanged:

This method is called when the text is changed, in case any subclasses would like to know. Within text, the lengthAfter characters beginning at start have just replaced old text that had length lengthBefore.

It is an error to attempt to make changes to text from this callback.

Have you tried using a TextWatcher, on your EditText? For instance:

editText.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override
      public void afterTextChanged(Editable s) {
        // This is only a sample code trying to reproduce your current behavior. 
        // I did not test it.
        String iban = s.toString().toUpperCase().replaceAll(" ", "");
        String compactIban = iban.replaceAll("[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}", "$0 ");
        s.replace(0, s.length(), compactIban);
      }
    });