Search code examples
javaandroidandroid-edittext

java.lang.IndexOutOfBoundsException: setSpan (N ... N) ends beyond length 10500


I get this exception when I call EditText.setSelection()

java.lang.IndexOutOfBoundsException: setSpan (N ... N) ends beyond length 10500

N can be any number. For example if I call setSelection(10476,10568) N will be 10568. But 10500 is constant.

          java.lang.IndexOutOfBoundsException: setSpan (10568 ... 10568) ends beyond length 10500
              at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1090)
              at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:665)
              at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:658)
              at android.text.Selection.setSelection(Selection.java:78)
              at android.widget.EditText.setSelection(EditText.java:91)
...

Are there any limitations of EditText that cause this?

Before I do a selection I load a text file which contains definitely more than 10500 characters as it contains ca. 12000 lines. And then I call EditText.setText() to put the file contents into the field. EditText.setText() works without any problems. First I thought there is something wrong with the file contents, but I loaded another file and when the selection occurred I got the same exception and it contained ends beyond length 10500


Solution

  • This is the actual method from android.text.SpannableStringBuilder where your code is failing.

    private void checkRange(final String operation, int start, int end) {
        if (end < start) {
            throw new IndexOutOfBoundsException(operation + " " +
                    region(start, end) + " has end before start");
        }
    
        int len = length();
    
        if (start > len || end > len) {
            throw new IndexOutOfBoundsException(operation + " " +
                    region(start, end) + " ends beyond length " + len);
        }
    
        if (start < 0 || end < 0) {
            throw new IndexOutOfBoundsException(operation + " " +
                    region(start, end) + " starts before 0");
        }
    }
    

    It looks like your start/end is greater than the length (calculated by length()) in the EditText. Probably a case of truncation.

    As far as number of characters an EditText can hold is not restricted from Android OS, but probably from device. See Max 9000 characters in Android TextView? and also https://groups.google.com/forum/#!topic/android-developers/JVAm8vBaIQg