Html.toHtml with Spanned cast (ClassCastException) <Android>

1.2k views Asked by At

Trying to format my output (in a TextView) using HTML. I need to get the text HTML-formating back from the old output, and add the new text one line above it.

String previous = Html.toHtml((Spanned) chatOutput.getText());
chatOutput.setText(Html.fromHtml(message + "<br>" + previous));

This compiles but gives a java.lang.ClassCastException: java.lang.String on runtime at the toHtml() method. I saw several people that suggested that the toHtml() method could be used that way, but maybe I'm missing something.

3

There are 3 answers

0
Cander On BEST ANSWER
TextView chatOutput = (TextView) findViewById(R.id.textView4);
chatOutput.setText("", BufferType.SPANNABLE);

void updateChatOutput {
    String previous = Html.toHtml((Spannable) chatOutput.getText());
    if (!previous.equals("")) {
        if (previous.substring(0, 13).equals("<p dir=\"ltr\">"))
            previous = previous.substring(13, previous.length()-3); //remove <p dir="ltr"> and </p>
        else
            previous = previous.substring(3, previous.length()-3); //remove <p> and </p>
    }
    chatOutput.setText(Html.fromHtml(message.substring(2, message.length()) + "<br>" +  previous));
}

Figured it out. Changing the cast to Spannable and have used the setText method with the BufferType.SPANNABLE solved the orginal problem.

Then a follow-up issue occurred, weird line braking in the textview. Turned out that html-paragraph code was added somewhere in this process, ugly solution below when manually deleting it. The solution got even more tacky when I realised that additonal parameters in the paragraph-statement was added by a device with API 18, compared my testing device with API 8.

1
marcinj On

From documentation for getText()

Return the text the TextView is displaying. If setText() was called with an argument of BufferType.SPANNABLE or BufferType.EDITABLE, you can cast the return value from this method to Spannable or Editable,

So you can cast it, but I would still check with instanceof if this is safe, what if textview was cleared with empty text?

0
live-love On

Same problem. Had to create new SpannableString before casting to Spanned.

Spanned spannedText = new SpannableString(textView.getText());
String htmlString = Html.toHtml(spannedText);