Every Android Developer is familiar with passing data via a Bundle or Intent.
In doing so, you would have wanted to pass your entire POJO (Plain Old Java Object) class,or List<Bean>. But Intent or Bundle don’t allow that right off the bat. The key lies in your Beans implementing Parcelable.
public class YourModel implements Parcelable {
// properties
String name, url;
public YourModel() { }
// Getter Setters here
// Parcelable methods
protected YourModel(Parcel in) {
name = in.readString();
url = in.readString();
// other properties
}
public static final Creator<YourModel> CREATOR = new Creator<YourModel>() {
@Override
public YourModel createFromParcel(Parcel in) {
return new YourModel(in);
}
@Override
public YourModel[] newArray(int size) {
return new YourModel[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(url);
// other properties
}
}
After that, you simply pass your model class data like this:
[su_row][su_column size=”1/2″]
Passing via Intent
intent.putParcelableArrayListExtra("listofmodels", (ArrayList<? extends Parcelable>) yourModels);
List of YourModel
intent.putExtra("singlemodel", (Parcelable) yourModel);
Single YourModel object
[/su_column] [su_column size=”1/2″]
Passing YourModel via a Bundle
bundle.putParcelableArrayList("listofmodels", (ArrayList<? extends Parcelable>) yourModels);
List of YourModel
bundle.putParcelable("singlemodel", yourModel);
Single YourModel object
[/su_column] [/su_row]
PRO-TIP:
You can alternatively implement Serializable to achieve a similar result!
USEFUL RESOURCES:
- Parceler library by John Ericksen
- Difference between Parcelable and Serializable