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
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
It will automatically create Parcelable.
And there is a webiste also for doing this. http://www.parcelabler.com/
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
out.writeInt(mBool ? 1 : 0); //Write
this.mBool =in.readInt()==1; //Read
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:
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);
}
...
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
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);