Search code examples
androidperformanceparcelable

Android Parcelable implemenation without getters and setters


In android developers documentation to avoid getters and setters Android Performance Pattern How create Parcelable implemented model class?


Solution

  • In android developers documentation to avoid getters and setters Android Performance Pattern

    No, it does not. The section on getters and setters is entitled "Avoid Internal Getters/Setters" (emphasis added). It refers to using getters and setters, as opposed to field access, inside a class. It does not suggest that getters and setters should be avoided in general.

    How create Parcelable implemented model class?

    You create all Parcelable classes the same way:

    • add implements Parcelable to the class definition
    • implement writeToParcel()
    • implement describeContents()
    • add the CREATOR static field

    None of that has anything to do with getters or setters. The MyParcelable sample class shown in the JavaDocs for Parcelable does not use a getter or a setter for the mData field.

    Similarly, using parcelabler.com, here is Parcelable implementation of a Chair:

    public class Chair implements Parcelable {
      private String material;
      private int numLegs;
    
        protected Chair(Parcel in) {
            material = in.readString();
            numLegs = in.readInt();
        }
    
        @Override
        public int describeContents() {
            return 0;
        }
    
        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(material);
            dest.writeInt(numLegs);
        }
    
        @SuppressWarnings("unused")
        public static final Parcelable.Creator<Chair> CREATOR = new Parcelable.Creator<Chair>() {
            @Override
            public Chair createFromParcel(Parcel in) {
                return new Chair(in);
            }
    
            @Override
            public Chair[] newArray(int size) {
                return new Chair[size];
            }
        };
    }
    

    It also does not use getters or setters.