Parcel, Classloader And Reading Null Values
I am trying to understand how to read null values from Parcel properly. Let's look my use case: public class MyModel implements Parcelable { private Long id; private String
Solution 1:
How about supply ClassLoader
with MyModel.class. getClassLoader()
?
Solution 2:
What is the best approach to read null values from Parcel in that case?
You can use the string-specific methods:
Parcel.writeString(String)
Parcel.readString()
They work perfectly well with null
values.
For example, assume you have a class with the following fields in it:
publicclassTestimplementsParcelable{
publicfinalint id;
privatefinalString name;
publicfinalString description;
...
You create the Parcelable
implementation like this (using Android Studio autoparcelable tool):
@OverridepublicvoidwriteToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(null); // NOTE the null value here
dest.writeString(description);
}
protectedTest(Parcel in) {
id = in.readInt();
name = in.readString();
description = in.readString();
}
Your Test.name
value will be deserialised as null
correctly, without requiring any casting to String
.
Solution 3:
I think the best way to do this is to write the length of string name
before name
. If name
is null, just write 0 as its length, and do not write name
. When reading, if length
is read and its value is zero, do not read name
and just set name
to null
.
Post a Comment for "Parcel, Classloader And Reading Null Values"