Implement Parcelable to Bundle your POJOs

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:

 Passing via Intent

intent.putParcelableArrayListExtra("listofmodels", (ArrayList<? extends Parcelable>) yourModels);

List of YourModel

intent.putExtra("singlemodel", (Parcelable) yourModel);

Single YourModel object

 Passing YourModel via a Bundle

bundle.putParcelableArrayList("listofmodels", (ArrayList<? extends Parcelable>) yourModels);

List of YourModel

bundle.putParcelable("singlemodel", yourModel);

Single YourModel object

PRO-TIP:
You can alternatively implement Serializable to achieve a similar result!

USEFUL RESOURCES:

Enjoyed this article? Please spread the word.

Subscribe to Newsletter
Be the first to get latest updates and exclusive content
straight to your email inbox.
STAY UPDATED
Chill, I hate spam too. You can unsubscribe anytime.

Suleiman

An App developer with an eye for design. Loves to create apps with good UI/ UX that people appreciate. In his spare time, he likes to draw and paint.

  • Victor

    I like save param name in POJO to avoid strings alone in code:

    public class YourModel implements Parcelable {
    public static final String PARAM = “YoutModelParam”

    and use:
    bundle. putExtra(YourModel.PARAM, yourModel);

    • Hi Victor,
      That’s a really neat approach to follow. I usually keep the Keys in my Activity or a Constants class, but I find your approach more intuitive. Thanks for sharing.

Enjoyed this article? Please spread the word.

Subscribe to Newsletter
Be the first to get latest updates and exclusive content
straight to your email inbox.
STAY UPDATED
Chill, I hate spam too. You can unsubscribe anytime.

Develop faster with a multi-purpose, ready to use App
GET THE CODE