0

I use the following code to get all spans in a spannable string.

SpannableStringBuilder str = new SpannableStringBuilder(editText.getText());
Object [] objectSpans = str.getSpans(0, str.length(), Object.class);

//loop through all spans
for (Object objSpan: objectSpans) {
   Spanned spanned = (Spanned) objSpan;// Here I encounter a ClassCastException
   start = spanned.getSpanStart(new Object());
   end = spanned.getSpanEnd(new Object());
   ...
}

I encounter a following ClassCastException when I want to cast objSpan to Spanned (in line 6).

java.lang.ClassCastException: android.text.style.SpellCheckSpan cannot be cast to android.text.Spanned

How can I solve this problem? Is there a better way to get all spans in a spannable string?

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
user6931342
  • 145
  • 3
  • 11

2 Answers2

1

Use instanceof instead doing the casting automatically.

for (Object objSpan: objectSpans) {
   if(objSpan instanceof Spanned){
    Spanned spanned = (Spanned) objSpan;// Here I encounter a ClassCastException
    start = spanned.getSpanStart(new Object());
    end = spanned.getSpanEnd(new Object());
    ...
   } 
}

To understand what's the problem you may read this ClassCastException Documentation so you can read :

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:

So, if you want to do a cast you have to make sure that object is the same type of what your are declaring, otherwise you'll get a ClassCastException

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
0

check if objSpan is instance of Spanned.. Seems like @Skizo thinks so as mine.therefore sorry for the repeated answer but it solved my problem too.

SpannableStringBuilder str = new SpannableStringBuilder(editText.getText());
Object [] objectSpans = str.getSpans(0, str.length(), Object.class);

//loop through all spans
for (Object objSpan: objectSpans) {
   if(objSpan instanceof Spanned){
   Spanned spanned = (Spanned) objSpan;// Here I encounter a ClassCastException
   start = spanned.getSpanStart(new Object());
   end = spanned.getSpanEnd(new Object());
   ...
}
}
Rezaul Karim
  • 830
  • 8
  • 15