Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Nulls be passed to parcel?

Is it possible to write null to Parcel when parcelling an object, and get null back again when unparcelling it again?

Let's assume we have the following code:

public class Test implements Parcelable {
    private String string = null;
    public Test(Parcel dest, int flags) {
        source.writeString(string);
    }
}

Will I get a NullPointerException when reading this value back from the parcel using Parcel.readString()?

Or will I get a null value out?

like image 988
Fattum Avatar asked Dec 19 '15 11:12

Fattum


1 Answers

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:

  • Parcel, ClassLoader and Reading Null values
like image 77
Richard Le Mesurier Avatar answered Oct 05 '22 10:10

Richard Le Mesurier