I'm developing an app for Android using Android Studio. I have to let the user insert a text into an EditText with a maximum length. For this aim I have employed a lengthFilter passing to it the maximum length.
Here the declaration:
etMessage.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxMessageLength)});
In another thread I execute the following code:
while (!startEncoding){
final String temp = etMessage.getText().toString();
if (!(Comparison.equals(temp))) {
Comparison = temp;
handler.post(new Runnable() {
@Override
public void run() {
tvNumCharacters.setText(Integer.toString(maxMessageLength - etMessage.length()));
}
});
}
}
These last lines just show into a TextView (tvNumCharacters) the residual numbers of characters the user can input when the string inside the EditText (temp) is different from the string previously contained in the EditText (Compare).
The Problem is: when the user deletes some characters (independetly from the actual length of the already inserted string) the following exception is raised:
AndroidRuntime: FATAL EXCEPTION: Thread-8364
Process: com.user.steganography, PID: 12057
java.lang.IndexOutOfBoundsException: getChars (0 ... 16) ends beyond length 15
at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1090)
at android.text.SpannableStringBuilder.getChars(SpannableStringBuilder.java:972)
at android.text.SpannableStringBuilder.toString(SpannableStringBuilder.java:994)
at com.user.steganography.Coding.checkTextLength(Coding.java:111)
at com.user.steganography.Coding.access$000(Coding.java:19)
at com.user.steganography.Coding$2.run(Coding.java:84)
at java.lang.Thread.run(Thread.java:818)
Sometimes it crashes when deleting just one character, other only when deleting more characters.
This happens when etMessage.getText().toString()
is recalled.
Could anyone suggest me a solution for this problem? I have already tried to change the attribute android:inputType
but it still not work.
[SOLUTION]
By using addTextChangedListener(TextWatcher watcher)
the problem of threading was avoided and everything works fine.