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:

[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:

Suleiman

Product Designer who occasionally writes code.

4 Responses

  1. Arvind Reddy says:

    Hi @suleiman19:disqus , I am working with Parcelable. When a “next” button is pressed, how do I go to next item in the custom array list without going back to the list and selecting next item

  2. Arvind Reddy says:

    Hi @suleiman19:disqus , I am working with Parcelable. When a “next” button is pressed, how do I go to next item in the custom array list without going back to the list and selecting next item

  3. Victor says:

    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);

    • Suleiman19 says:

      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.

Leave a Reply

Your email address will not be published. Required fields are marked *