Reputation: 332
In android developers documentation to avoid getters and setters Android Performance Pattern How create Parcelable implemented model class?
Upvotes: 0
Views: 717
Reputation: 1007296
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:
implements Parcelable
to the class definitionwriteToParcel()
describeContents()
CREATOR
static
fieldNone 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.
Upvotes: 1
Reputation: 76942
you just need to assign values directly to the variables.
private String item1;
private String item2;
public ClassName(String item1, String item2) {
this.item1 = item1;
this.item2 = item2;
}
protected ClassName(Parcel in) {
this.item1 = in.readString();
this.item2 = in.readString();
}
@Override
public int describeContents() { return 0; }
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.item1);
dest.writeString(this.item2);
}
public static final Creator<ClassName> CREATOR = new Creator<ClassName>() {
@Override
public ClassName createFromParcel(Parcel source) {return new ClassName(source);}
@Override
public ClassName[] newArray(int size) {return new ClassName[size];}
};
Upvotes: 0