Search code examples
androidparcelableparcel

Passing custom class objects using parcelable


How can i access custom class object in a class implementing parcelable

I have a parcelable class as folows

class A implements Parcelable{
      private CustomClass B;
}

Is it possible to use that custom class as a normal variable during writeToParcel() and readParcel(Parcel in)

PS: I can't implement parcelable on class B as it is in Non-Android module


Solution

  • In your comment you say that CustomClass is made of 4 integer variables. You could therefore do something like this:

    class A implements Parcelable {
    
        private CustomClass B;
    
        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(B.getFirst());
            dest.writeInt(B.getSecond());
            dest.writeInt(B.getThird());
            dest.writeInt(B.getFourth());
        }
    
        private A(Parcel in) {
            B = new CustomClass();
            B.setFirst(dest.readInt());
            B.setSecond(dest.readInt());
            B.setThird(dest.readInt());
            B.setFourth(dest.readInt());
        }
    }