Can Nulls be passed to parcel?

谁说胖子不能爱 提交于 2019-12-05 12:03:59
Richard Le Mesurier

Yes, you can pass a null to the Parcel.writeString(String) method.

When you read it out again with Parcel.readString(), you will get a null value out.


For example, assume you have a class with the following fields in it:

public class Test implements Parcelable {
    public final int id;
    private final String name;
    public final String description;
    ...

You create the Parcelable implementation like this (using Android Studio autoparcelable tool):

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(id);
    dest.writeString(null); // NOTE the null value here
    dest.writeString(description);
}

protected Test(Parcel in) {
    id = in.readInt();
    name = in.readString();
    description = in.readString();
}

When running this code, and passing a Test object as a Parcelable extra in an Intent, 2 points become apparent:

  1. the code runs perfectly without any NullPointerException
  2. the deserialised Test object has a value name == null

You can see similar info in the comments to this related question:

In my case (Kotlin)

 override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeInt(if (PapperId == null) -1 else PapperId)
        parcel.writeString( if (Nome == null) "" else Nome)
}

If you want to write other data types such as Integer, Double, Boolean with possible null values to a parcel, you can use Parcel.writeSerializable().

When reading these values back from parcel, you have to cast the value returned by Parcel.readSerializable() to the correct data type.

Double myDouble = null;
dest.writeSerializable(myDouble);  // Write

Double readValue = (Double) dest.readSerializable();   // Read
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!