Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read/write a boolean when implementing the Parcelable interface?

I'm trying to make an ArrayList Parcelable in order to pass to an activity a list of custom object. I start writing a myObjectList class which extends ArrayList<myObject> and implement Parcelable.

Some attributes of MyObject are boolean but Parcel don't have any method read/writeBoolean.

What is the best way to handle this?

like image 588
grunk Avatar asked Jun 01 '11 12:06

grunk


People also ask

How do you implement Parcelable?

Create Parcelable class without plugin in Android Studioimplements Parcelable in your class and then put cursor on "implements Parcelable" and hit Alt+Enter and select Add Parcelable implementation (see image). that's it.

What is a primary purpose of the Parcelable interface?

The Parcelable interface adds methods to all classes you want to be able to transfer between activities. These methods are how parcelable deconstructs the object in one activity and reconstructs it in another.

What is Parcelable data?

A Parcelable is the Android implementation of the Java Serializable. It assumes a certain structure and way of processing it. This way a Parcelable can be processed relatively fast, compared to the standard Java serialization.

What is Parcelable Kotlin?

Save. In Android, to pass the data from one activity to another activity, we use the Parcelable. The kotlin-parcelize plugin provides a Parcelable implementation generator. The Android's Parcelable is an interface on which, the values can be written and read from a Parcel.


2 Answers

Here's how I'd do it...

writeToParcel:

dest.writeByte((byte) (myBoolean ? 1 : 0));     //if myBoolean == true, byte == 1 

readFromParcel:

myBoolean = in.readByte() != 0;     //myBoolean == true if byte != 0 
like image 162
b_yng Avatar answered Oct 02 '22 08:10

b_yng


You could also make use of the writeValue method. In my opinion that's the most straightforward solution.

dst.writeValue( myBool ); 

Afterwards you can easily retrieve it with a simple cast to Boolean:

boolean myBool = (Boolean) source.readValue( null ); 

Under the hood the Android Framework will handle it as an integer:

writeInt( (Boolean) v ? 1 : 0 ); 
like image 23
Taig Avatar answered Oct 02 '22 08:10

Taig