Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve from a Parcel a CharSequence that was saved using TextUtils.writeToParcel(...)?

I want to be able to send formatted text (i.e., text with format spans) from one of my app activities to another. These CharSequence instances live deep inside some Parcelable types that I created.

For instance, when marshalling one of the types that carries formatted CharSequences I use TextUtils.writeToParcel as follows:

public class HoldsCharSequence {

    /* some formatted string that uses basic spans (e.g., ForegroundColorSpan) */
    private CharSequence cs;

    public void writeToParcel(Parcel out, int flags) {
        TextUtils.writeToParcel(cs, out, 0);
    }

    /* ... rest of the code ... */
}

The problem is that I don't know how to retrieve the CharSequence from the Parcel in my private constructor.

The following does not work:

private HoldsCharSequence(Parcel in) {
    cs = (CharSequence) in.readValue(CharSequence.class.getClassLoader());
}

I get the following error:

android.os.BadParcelableException: ClassNotFoundException when unmarshalling

Two more things: 1. I have already succesfully implemented my own custom Parcelable objects, the problem is with CharSequences in particular. 2. I know that TextUtils.writeToParcel will do a best-effort job at saving the text format, I can live with that.

like image 979
gdecaso Avatar asked Mar 28 '12 21:03

gdecaso


1 Answers

In case someone else is interested, I found the answer in this post.

The correct way to retrieve CharSequences that were stored in a Parcel using TextUtils.writeToParcel(...) is

cs = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
like image 139
gdecaso Avatar answered Oct 11 '22 15:10

gdecaso