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
cl
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.
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 );
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.
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;
...
}
you declare like this
private boolean isSelectionRight;
write
out.writeInt(isSelectionRight ? 1 : 0);
read
isSelectionRight = (in.readInt() == 0) ? false : true;
boolean type needs to be converted to something that Parcel supports and so we can convert it to int.
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});