How to serialize null value when using Parcelable interface How to serialize null value when using Parcelable interface android android

How to serialize null value when using Parcelable interface


You can use Parcel.writeValue for marshalling generic object with null value.


I'm using a Parcelable class that has Integer and Boolean fields as well, and those fields can be null.

I had trouble using the generic Parcel.writeValue method, particularly when I was trying to read it back out via Parcel.readValue. I kept getting a runtime exception that said it couldn't figure out the type of the parceled object.

Ultimately, I was able to solve the problem by using Parcel.writeSerializable and Parcel.readSerializable with a type cast, as both Integer and Boolean implement the Serializable interface. The read and write methods handle null values for you.


This is the solution I came up with to write strings safely:

private void writeStringToParcel(Parcel p, String s) {    p.writeByte((byte)(s != null ? 1 : 0));    p.writeString(s);}private String readStringFromParcel(Parcel p) {    boolean isPresent = p.readByte() == 1;    return isPresent ? p.readString() : null;}