android: how to persistently store a Spanned?

I had a similar problem; I used a SpannableStringBuilder to hold a string and a bunch of spans, and I wanted to be able to save and restore this object. I wrote this code to accomplish this manually using SharedPreferences:

    // Save Log
    SpannableStringBuilder logText = log.getText();
    editor.putString(SAVE_LOG, logText.toString());
    ForegroundColorSpan[] spans = logText
            .getSpans(0, logText.length(), ForegroundColorSpan.class);
    editor.putInt(SAVE_LOG_SPANS, spans.length);
    for (int i = 0; i < spans.length; i++){
        int col = spans[i].getForegroundColor();
        int start = logText.getSpanStart(spans[i]);
        int end = logText.getSpanEnd(spans[i]);
        editor.putInt(SAVE_LOG_SPAN_COLOUR + i, col);
        editor.putInt(SAVE_LOG_SPAN_START + i, start);
        editor.putInt(SAVE_LOG_SPAN_END + i, end);
    }

    // Load Log
    String logText = save.getString(SAVE_LOG, "");
    log.setText(logText);
    int numSpans = save.getInt(SAVE_LOG_SPANS, 0);
    for (int i = 0; i < numSpans; i++){
        int col = save.getInt(SAVE_LOG_SPAN_COLOUR + i, 0);
        int start = save.getInt(SAVE_LOG_SPAN_START + i, 0);
        int end = save.getInt(SAVE_LOG_SPAN_END + i, 0);
        log.getText().setSpan(new ForegroundColorSpan(col), start, end, 
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

I my case I knew that all the spans were of type ForegroundColorSpan and with flags SPAN_EXCLUSIVE_EXCLUSIVE, but this code can be easily adapted to accomodate other types.


Right now, Html.toHtml() is your only built-in option. Parcelable is used for inter-process communication and is not designed to be durable. If toHtml() does not cover all the particular types of spans that you are using, you will have to cook up your own serialization mechanism.

Since saving the object involves disk I/O, you should be doing that in a background thread anyway, regardless of the speed of toHtml().