Updated 23 June 2017
There is the problem, how can pass the custom class (POJO) object data or list data from one Activity to another activity via intent.?
We can be done it very easily by using Parcelable Interface. We implement Parcelable Interface and override its methods in our POJO classes and pass our POJO class object by intent.putExtra(“key”, object) or list of Parcelable object intent.putParcelableArrayListExtra(“key”, object_list).
For example-
1 2 3 4 5 6 |
Intent intent = new Intent(mContext, NewViewSimpleProduct.class); intent.putExtra("idOfProduct", mDataset.get(Integer.parseInt(indexFlagPair[0])).getProductId()); intent.putExtra("nameOfProduct", mDataset.get(Integer.parseInt(indexFlagPair[0])).getProductName()); intent.putParcelableArrayListExtra("nextpreviousIds", nextPrevProductIds); intent.putExtra("abc", new NextPrevProductId("1234", "Nokia")); mContext.startActivity(intent); |
and get this object in NewViewSimpleProduct Activity as-
1 2 |
NextPrevProduct nextPrevProductId = extras.getParcelable("id"); ArrayList<NextPrevProduct> nextPrevProductIds = extras.getParcelableArrayList("nextpreviousIds"); |
But after getting the parcel object on receiving Activity, we can get a null value for all members of the object. So, how we solve this mistake?
This is the normal mistake we can solve it only few work to take care. i.e. we just Override writeToParcel() method and write the value of all members in synchronous, we will get all members value just add a constructor with Parcel argument and assign values to all object members in this constructor in synchronous form as we write in writeToParcel() method.
for Example-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public class NextPrevProductId implements Parcelable { public String productName, productId; public NextPrevProductId(String productId, String productName){ this.productId = productId; this.productName = productName; } protected NextPrevProductId(Parcel in) { this.productId = in.readString(); this.productName = in.readString(); } public static final Creator<NextPrevProductId> CREATOR = new Creator<NextPrevProductId>() { @Override public NextPrevProductId createFromParcel(Parcel in) { return new NextPrevProductId(in); } @Override public NextPrevProductId[] newArray(int size) { return new NextPrevProductId[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(productId); dest.writeString(productName); } @Override public String toString(){ return productId + " => " + productName; } } |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.