I\'m trying to make my objects Parcelable. However, I have custom objects and those objects have ArrayList
attributes of other custom objects I have made.
I have found simplest way to create Parcelable class
Android Parcelable code generator
public class Sample {
int id;
String name;
}
It is very easy, you can use a plugin on android studio to make objects Parcelables.
public class Persona implements Parcelable {
String nombre;
int edad;
Date fechaNacimiento;
public Persona(String nombre, int edad, Date fechaNacimiento) {
this.nombre = nombre;
this.edad = edad;
this.fechaNacimiento = fechaNacimiento;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.nombre);
dest.writeInt(this.edad);
dest.writeLong(fechaNacimiento != null ? fechaNacimiento.getTime() : -1);
}
protected Persona(Parcel in) {
this.nombre = in.readString();
this.edad = in.readInt();
long tmpFechaNacimiento = in.readLong();
this.fechaNacimiento = tmpFechaNacimiento == -1 ? null : new Date(tmpFechaNacimiento);
}
public static final Parcelable.Creator<Persona> CREATOR = new Parcelable.Creator<Persona>() {
public Persona createFromParcel(Parcel source) {
return new Persona(source);
}
public Persona[] newArray(int size) {
return new Persona[size];
}
};}
To put:
bundle.putSerializable("key",(Serializable) object);
To get:
List<Object> obj = (List<Object>)((Serializable)bundle.getSerializable("key"));
Now you can use Parceler library to convert your any custom class in parcelable. Just annotate your POJO class with @Parcel. e.g.
@Parcel
public class Example {
String name;
int id;
public Example() {}
public Example(int id, String name) {
this.id = id;
this.name = name;
}
public String getName() { return name; }
public int getId() { return id; }
}
you can create an object of Example class and wrap through Parcels and send as a bundle through intent. e.g
Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));
Now to get Custom Class object just use
Example example = Parcels.unwrap(getIntent().getParcelableExtra("example"));