How to Read and Write Booleans in a Parcelable Class
If your class has a Boolean attribute and you need to implement Parcelable, then this short article is exactly for you. Let’s get started!
💡 Tips: If you need a refresher on how to implement Parcelable, please refer to my short series of articles 👍 :
Demo Class
This is the class we will be working with, House
. It has a Boolean attribute, isNearSchool
. Take your time to go through the code and when you’re ready please continue reading 👌
Writing Booleans
To write a Boolean to the parcel you can use this syntax in the writeToParcel
method:
parcel.writeInt(<variable> ? 1 : 0);
Here you can see the full code:
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(isNearSchool ? 1 : 0);
}
A Closer Look 🔍
Let’s take a closer look at this expression:
<variable> ? 1 : 0
This means that if <variable>
is true
, the integer will be 1
and if <variable>
is false
, the integer will be 0
.
(In this case we replace <variable>
with isNearSchool
)
true → 1false → 0
Reading Booleans
To read a Boolean from the parcel you can use this syntax in the House
constructor that takes a Parcel as argument:
in.readInt() == 1
Here you can see the full code:
protected House(Parcel in) {
isNearSchool = in.readInt() == 1;
}
A Closer Look 🔍
Let’s take a closer look at this expression:
in.readInt() == 1
Our logic to write the boolean to the parcel was:
true → 1false → 0
We had a Boolean and we transformed it into an int.
Now, to read the value we need to keep the same logic but in reverse because we will read an int and we have to transform it into the corresponding Boolean:
1 → true0 → false
To do this, we can check if the int we read is 1 and this will keep our logic intact:
isNearSchool = in.readInt() == 1;
If the value is 1
, the boolean assigned to isNearSchool
will be true
, else it will befalse
. ✅ Exactly what we need.
1 → true0 → false
👏 I hope you found this article helpful. You claps are very appreciated to help others find this article 😃 . Thank you very much in advance!