I understand that IndexOutOfBounds exception is the most common error, but in my case it is showing up in some devices and working perfectly fine on others. What I was trying to do is get the last typed character in a Edittext and replace it with another character with the help of TextWatcher like this.
public TextWatcher textWatcher = new TextWatcher() {
int selPos;
boolean isNotBackspace = true;
private String newTypedString = "";
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
selPos = editText.getSelectionStart();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
isNotBackspace = count > before;
newTypedString = s.subSequence(start, start + count).toString();
}
@Override
public void afterTextChanged(Editable s) {
editText.removeTextChangedListener(this);
if (s.length() == 0) {
isNotBackspace = true;
} else if (isNotBackspace) {
s.replace(editText.getSelectionEnd()-1, editText.getSelectionEnd(), changeTextChar(newTypedString));
}
editText.addTextChangedListener(this);
}
};
For Clarification:
The changeTextChar() is my custom method that provides a symbol when a character is passed. The backspace code is because I do not want to replace backspace with anything.
Problem:
I am getting a runtime exception on afterTextChanged() which is caused by IndexOutOfBoundsException: replace (-1 ... 0) starts before 0
To my understanding, without writing anything TextWatcher will not invoke so in which case the index value is -1? Is there any alternative way to solve this? This error is appearing only in some devices, for other it just works fine.