417

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?

13
  • 3
    Because all the reading i have done about passing object between activities preconise the use of parcelable instead of serialisable.
    – grunk
    Jun 1, 2011 at 13:01
  • 10
    @MisterSquonk You should not use the Serializable interface for inter-activity communication. It is slow. Jun 1, 2011 at 13:05
  • 1
    @grunk: OK, that's fair enough but until Intent.putExtra(String name, Serializable value) is marked as deprecated in the docs, I'll be happy to continue using it if it makes life easier for me. Just a thought.
    – Squonk
    Jun 1, 2011 at 13:06
  • 3
    @Octavian: But that depends on a per-case study and is relative.
    – Squonk
    Jun 1, 2011 at 13:07
  • 2
    in my oppinion, the architect team of android is lazy!!! whereis boolean!!!!!!!!
    – Mateus
    Mar 8, 2013 at 12:30

14 Answers 14

964

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
9
  • 41
    No reason to use byte over int. byte is more verbose because of the cast: dest.writeInt(myBoolean ? 1 : 0);
    – miguel
    Jan 17, 2015 at 2:31
  • Why did @SiPlus comment get so many upvotes? Neither 1, nor 0 is "loaded" at all. It makes absolutely no difference. And since when is Java a weakly-typed language?
    – noone
    Jun 17, 2015 at 6:45
  • 14
    @sotrh writing a byte just writes an int: /** * Write a byte value into the parcel at the current dataPosition(), * growing dataCapacity() if needed. */ public final void writeByte(byte val) { writeInt(val); }
    – Dallas
    Oct 13, 2015 at 2:14
  • 3
    @Dallas is that from the documentation? If so then disregard my comment. Seems disingenuous for the api to have a function that says writeByte, but actually writes an int.
    – sotrh
    Oct 13, 2015 at 2:21
  • 1
    @sotrh that is a copy-paste from a source code. Open android.os.Parcel source and see for yourself. Jan 5, 2016 at 10:19
70

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 );
4
  • android source showing the "under the hood" part (l. 1219). Though a tiny bit less efficient (because of the method call and the switch) this method reads a bit more straightforward.
    – desseim
    Feb 12, 2014 at 18:08
  • 6
    The code as written here will not compile. readValue requires a classloader but it's not needed for Booleans. It should read "boolean myBool = (Boolean) source.readValue(null);" Reviewers that have no idea what they're doing and rejected my edit to this answer: @hemang, jeeped, DavidRR.
    – miguel
    Jan 27, 2015 at 0:28
  • 1
    @miguel That's true, fixed it :)
    – Taig
    Jan 27, 2015 at 1:35
  • It's better to not mess with classLoaders for this simple task.
    – JohnyTex
    Jan 15, 2021 at 8:47
21

you declare like this

 private boolean isSelectionRight;

write

 out.writeInt(isSelectionRight ? 1 : 0);

read

isSelectionRight  = in.readInt() != 0;

boolean type needs to be converted to something that Parcel supports and so we can convert it to int.

1
  • This causes an error, incompatible types, required boolean found int?
    – Paul Okeke
    May 23, 2015 at 22:46
16

AndroidStudio (using 2.3 atm), after implementing Parcelable on your class, you can simply hold your mouse pointer over your class name and it asks you to add the parcelable implementation:

enter image description here

From the four fields, it generates the following:

public class YourClass implements Parcelable{

String someString;
int someInt;
boolean someBoolean;
List<String> someList;

protected YourClass(Parcel in) {
    someString = in.readString();
    someInt = in.readInt();
    someBoolean = in.readByte() != 0;
    someList = in.createStringArrayList();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(someString);
    dest.writeInt(someInt);
    dest.writeByte((byte) (someBoolean ? 1 : 0));
    dest.writeStringList(someList);
}

...
1
  • 1
    This is handy :)
    – Dino Tw
    Nov 17, 2017 at 21:21
8

I normally have them in an array and call writeBooleanArray and readBooleanArray

If it's a single boolean you need to pack, you could do this:

parcel.writeBooleanArray(new boolean[] {myBool});
1
8
out.writeInt(mBool ? 1 : 0); //Write
this.mBool =in.readInt()==1; //Read
6

Short and simple implementation in Kotlin, with nullable support:

Add methods to Parcel

fun Parcel.writeBoolean(flag: Boolean?) {
    when(flag) {
        true -> writeInt(1)
        false -> writeInt(0)
        else -> writeInt(-1)
    }
}

fun Parcel.readBoolean(): Boolean? {
    return when(readInt()) {
        1 -> true
        0 -> false
        else -> null
    }
}

And use it:

parcel.writeBoolean(isUserActive)

parcel.readBoolean()        // For true, false, null
parcel.readBoolean()!!      // For only true and false
3
  • @AliKazi you can't do this in 1 line statement in Java with support optional types. You should persist 3 states. I think you forget about null. Apr 17, 2018 at 23:22
  • @comm1x, The IDE does not like this solution. `Cannot access "readBoolean" before superclass constructor has been called. Sep 25, 2018 at 18:43
  • @comm1x I resolved the issue. In order to work the added methods must be within the companion object Sep 25, 2018 at 19:46
5

I suggested you the easiest way to implement Parcelable if you are using Android Studio.

Simply go to File->Settings->Plugins->Browse Repository and search for parcelable .See image

enter image description here It will automatically create Parcelable.

And there is a webiste also for doing this. http://www.parcelabler.com/

0
3

You could pack your boolean values into a byte using masking and shifting. That would be the most efficient way to do it and is probably what they would expect you to do.

4
  • +1. True, saving the value in a byte would be more efficient. Would you mind me editing my question to represent your idea? Jun 1, 2011 at 12:54
  • You can, but what you have written isn't really what I meant. It will work but isnt the most efficient. You can pack 8 booleans into a byte using masks and boolean algebra
    – fleetway76
    Jun 1, 2011 at 13:11
  • On most cases I agree with you, however I do have cases that creep up from time to time where I need three states that Boolean works will with. Such as an optional yes/no question. I need the null to know whether the Boolean has explicitly been specified or not. Nov 9, 2011 at 4:23
  • There is no reason using byte over int, since the Parcel's writeByte() method directly calls writeInt() Jan 5, 2016 at 10:27
3

It is hard to identify the real question here. I guess it is how to deal with booleans when implementing the Parcelable interface.

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

You will have to either store the value as a string or as a byte. If you go for a string then you'll have to use the static method of the String class called valueOf() to parse the boolean value. It isn't as effective as saving it in a byte tough.

String.valueOf(theBoolean);

If you go for a byte you'll have to implement a conversion logic yourself.

byte convBool = -1;
if (theBoolean) {
    convBool = 1;
} else {
    convBool = 0;
}

When unmarshalling the Parcel object you have to take care of the conversion to the original type.

1
  • There is absolutely no reason using String. There is no reason using byte over int, since the Parcel's writeByte() method directly calls writeInt(). The conversion logic is too verbose. Just do writeInt(boolean ? 1 : 0) and boolean = readInt() != 0 Jan 5, 2016 at 10:23
1

This question has already been answered perfectly by other people, if you want to do it on your own.

If you prefer to encapsulate or hide away most of the low-level parceling code, you might consider using some of the code I wrote some time ago for simplifying handling of parcelables.

Writing to a parcel is as easy as:

parcelValues(dest, name, maxSpeed, weight, wheels, color, isDriving);

where color is an enum and isDriving is a boolean, for example.

Reading from a parcel is also not much harder:

color = (CarColor)unparcelValue(CarColor.class.getClassLoader());
isDriving = (Boolean)unparcelValue();

Just take a look at the "ParceldroidExample" I added to the project.

Finally, it also keeps the CREATOR initializer short:

public static final Parcelable.Creator<Car> CREATOR =
    Parceldroid.getCreatorForClass(Car.class);
1
  • Thanks for .class.getClassLoader().
    – CoolMind
    Jan 21, 2019 at 6:47
1

There are many examples in the Android (AOSP) sources. For example, PackageInfo class has a boolean member requiredForAllUsers and it is serialized as follows:

public void writeToParcel(Parcel dest, int parcelableFlags) {
    ...
    dest.writeInt(requiredForAllUsers ? 1 : 0);
    ...
}

private PackageInfo(Parcel source) {
    ...
    requiredForAllUsers = source.readInt() != 0;
    ...
}
0

For API 29 and above we can use

writeToParcel:

dest.writeBoolean(booleanFlag);

readFromParcel:

booleanFlag = in.readBoolean()

Or We can use

writeToParcel:

dest.writeByte((byte) (booleanFlag ? 1 : 0));

readFromParcel:

booleanFlag = in.readByte() != 0;

0

Since api 29, you can now use the readBoolean() in the Parcel class. see https://developer.android.com/reference/android/os/Parcel#readBoolean() for more

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.