1

I had a strange error occuring with TextWatcher firing multiple times with different inputs on a single change of text, mainly on entering or removing spaces.

After some investigation I got following results on "afterTextChanged":
Test 1, enter space in String "Suger" -> "Su gar":

  1. "gar"
  2. " "
  3. "Su"
  4. "Su gar"

Test 2, enter another space in String "Su gar" -> "Su ga r":

  1. "Su r"
  2. "Su "
  3. "Su ga "
  4. "Su ga r"

I've already found a related question suggesting to shut down text suggestions (which I want to keep) or just take the first call (which is plain wrong in my tests): TextWatcher events are being fired multiple times

Theoretically I could just take every event and update everytime because the last one is correct, but I really don't want 3-4 updates in my viewmodel, when one should do the trick.

Has anyone encountered this problem too and has a viable solution?

If needed I can add some code, but I'm really just using the default implementation of a Textwatcher set to an EditText.

DaJohn
  • 45
  • 5
  • Are you interested in limiting events with an interval duration threshold? e.g. debouncing events with a delay of maybe 100ms. – rupinderjeet Jul 25 '21 at 09:46
  • I don't think that'd be efficient, – Richard Onslow Roper Jul 25 '21 at 11:20
  • I've already seen a proposed solution using a debouncer, but if I understood correctly that would get me the first event and skip all events in the next xxx ms. But since the first trigger is not the correct value I might loose the final, correct input which only available in the last event – DaJohn Jul 26 '21 at 11:31

1 Answers1

0

For the record, any other people who might run into the same issue:

I've just sat down with new energy for this topic and managed to solve it without using a debouncer or deactivating my autocomplete functionby removing the textwatcher completely.

Instead I used a focusListener like this:

   int pos = this.getAbsoluteAdapterPosition();
    et_text.setOnFocusChangeListener((v, hasFocus) -> {
        if (!hasFocus) {
            updateText(pos, et_text.getText().toString());
        }
    });

With that in place, I do only get the final result of the text entered by a user, without any events triggered in between. There still is a slight issue currently, since the User can enter something and then press my save-Button and his input is lost (due to focus not having changed), but that's a minor issue and I'm sure there's help for that, too.

DaJohn
  • 45
  • 5