Search code examples
androidparcelable

How to write to arraylist of two or more custom objects in Parcelable?


I have browsed the question on Stack and I found no question facing the particular problem. I have a class with two arraylist of custom objects. I am not sure how to implement writeToParcel for the parent class now. One option I found were readTypedList constructor, but I cant implement it twice. There is no readTypedListArray constructor that I can create an array ans send it.

Just a reminder the object are ArrayList and there are two such objects in the parent class. The github link for reference is here.

https://github.com/legalimpurity/PopularMoviesStage2/tree/master/app/src/main/java/popularmoviesstage1/legalimpurity/com/popularmoviesstage2/objects


Solution

  • You can add customArray using following way :

    In MovieObject class:

      @Expose
      private ArrayList< ReviewObject > ReviewObjs = new ArrayList< ReviewObject >();
      private ArrayList< TrailerVideoObject > TrailerVideoObjs = new ArrayList< TrailerVideoObject >();
    

    writeToParcel() :

     public void writeToParcel(Parcel dest, int flags) {
            dest.writeTypedList(ReviewObjs);
            dest.writeTypedList(TrailerVideoObjs);
        }
    

    and readFromParcel() :

    private void readFromParcel(Parcel in) {
    
        ReviewObjs = new ArrayList<ReviewObject>();
        in.readTypedList(ReviewObjs, ReviewObject.CREATOR);
    
        TrailerVideoObjs = new ArrayList<TrailerVideoObject>();
        in.readTypedList(TrailerVideoObjs, TrailerVideoObject.CREATOR);
    
      }
    

    And add following lines in CustomClasses :

    for ReviewObject :

    public class ReviewObject implements Parcelable {
        public static final Creator<ReviewObject> CREATOR = new Creator<ReviewObject>() {
            public ReviewObject createFromParcel(Parcel in) {
                return new ReviewObject(in);
            }
    
            public ReviewObject[] newArray(int size) {
                return new ReviewObject[size];
            }
    
        };
    // add other objects...
    }
    

    for TrailerVideoObject :

    public class TrailerVideoObject implements Parcelable {
        public static final Creator<TrailerVideoObject> CREATOR = new Creator<TrailerVideoObject() {
            public TrailerVideoObject createFromParcel(Parcel in) {
                return new TrailerVideoObject(in);
            }
    
            public TrailerVideoObject[] newArray(int size) {
                return new TrailerVideoObject[size];
            }
    
        };
    // add other objects...
    }