you need to implement an interface Parcelable
import android.os.Parcel;
import android.os.Parcelable;
public class UserParcelable implements Parcelable {
private Integer mID;
private String mName;
private String mDescription;
...
}
and override the following method:
- writeToParcel(Parcel out, int flags): You should implement serialization of the object.
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mID);
out.writeString(mName);
out.writeString(mDescription);
}
- describeContents(): You should define the kind of object, for instance using hashCode().
@Override
public int describeContents() {
return hashCode();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((mDescription == null) ? 0 : mDescription.hashCode());
result = prime * result + ((mID == null) ? 0 : mID.hashCode());
result = prime * result + ((mName == null) ? 0 : mName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserParcelable other = (UserParcelable) obj;
if (mDescription == null) {
if (other.mDescription != null)
return false;
} else if (!mDescription.equals(other.mDescription))
return false;
if (mID == null) {
if (other.mID != null)
return false;
} else if (!mID.equals(other.mID))
return false;
if (mName == null) {
if (other.mName != null)
return false;
} else if (!mName.equals(other.mName))
return false;
return true;
}
- Object CREATOR: You should implement de-serialize your custom data objects from Parcel.
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public UserParcelable createFromParcel(Parcel in) {
return new UserParcelable(in);
}
public UserParcelable[] newArray(int size) {
return new UserParcelable[size];
}
};
- Constructor: You should define a constructor with parcel as argument.
UserParcelable(Parcel in) {
mID = in.readInt();
mName = in.readString();
mDescription = in.readString();
}
It is important to note that using parcelable object than serializable object is sometimes up to 15 times faster. (http://blog.rocapal.org/?p=560)
No hay comentarios:
Publicar un comentario