Android: converting between Strings, SpannedStrings and Spannablestrings-ThrowExceptions

Exception or error:

I have a string resource called “foo”. It may be a simple string… or it may contain HTML. This may change over time: I should be able to box it up as at least a SpannableString immediately upon reading whether it’s HTML or not (but how??)

I want to get that raw CharSequence and first be able to display it as-is (the exact characters, not Android’s “interpretation” of it). Right now I can’t do that… toString() decides to rip out the parts it doesn’t think I want to see.

I’d then like to be able to create a SpannableString from this and other Strings or SpannableStrings via concatenation using some method (none of the normal ones work). I’d like to then use that SpannableString to display the HTML-formatted text in a TextView.

This shouldn’t be difficult, but clearly I’m not doing it right (there’s very little info out there about this that I’ve found so far). Surely there is a way to accurately interconvert between between Strings, SpannedStrings and even Spannablestrings, without losing the markups along the way?

Note that I’ve already played with the somewhat broken Linkify, but I want better control over the process (no dangling unformatted “/”s, proper hrefs, etc.) I can get this all to work IF I stay in HTML at all steps, though I can’t concatenate anything.

Edit 1: I’ve learned I can use the following to always ensure I get my raw string (instead of whatever Android decides it thinks the CharSequence really is). Nice… now, how to coax this into a SpannableString?

<string name="foo"><![CDATA[
    <b>Some bold</b>

Edit 2: Not sure why this didn’t work earlier, but… if foo1 and foo2 are strings marked up as above (as CDATA), then one can apparently do this:

String foo1 = (String)getResources().getText(R.string.foo1);
String foo2 = (String)getResources().getText(R.string.foo2);
SpannedString bar = new SpannedString(Html.fromHtml(foo1+foo2));

Curious: is there a more straightforward solution than this? Is this CDATA business actually necessary? It seems convoluted (but not as convoluted as never quite knowing what the resource type will be… String, Spannable, etc.)

How to solve:

It appears there isn’t a more straightforward way to accomplish this.


I had the same problem. There are two solutions according to Google API Guides.

First is to escape < mark with &lt; in the string resource. Unfortunately, String conversion removes the tag in the background.

Second is to use Format Strings instead of XML/HTML tags. It seems simpler, faster, and evades hidden conversion problems. getString(resource, ...) works like a printf(string, ...) here.

Both work and require some code to replace given part of the string anyway (handle tags or format strings). Enjoy! =)

Leave a Reply

Your email address will not be published. Required fields are marked *