Last active
June 10, 2016 13:10
-
-
Save OneCricketeer/10002360 to your computer and use it in GitHub Desktop.
Android: Abstract Parcelable Object Wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class DataParcel<D> implements IDataParcel<D> { | |
protected D data; | |
public DataParcel(D data) { | |
this.data = data; | |
} | |
public DataParcel(Parcel in) { | |
readFromParcel(in); | |
} | |
@Override | |
public D getData() { | |
return this.data; | |
} | |
public abstract void readFromParcel(Parcel in); | |
@Override | |
public int describeContents() { | |
// TODO Auto-generated method stub | |
return 0; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IDataParcel<D> extends Parcelable { | |
public D getData(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UserParcel extends DataParcel<User> { | |
public UserParcel(User user) { | |
super(user); | |
} | |
public UserParcel(Parcel in) { | |
super(in); | |
} | |
@Override | |
public void writeToParcel(Parcel dest, int flags) { | |
dest.writeString(data.getID()); | |
dest.writeString(data.getDisplayName()); | |
dest.writeString(data.getEmail()); | |
} | |
@Override | |
public void readFromParcel(Parcel in) { | |
data = new User(); | |
data.setID(in.readString()); | |
data.setDisplayName(in.readString()); | |
data.setEmail(in.readString()); | |
} | |
public static final Parcelable.Creator<UserParcel> CREATOR = new Parcelable.Creator<UserParcel>() { | |
@Override | |
public UserParcel createFromParcel(Parcel in) { | |
return new UserParcel(in); | |
} | |
@Override | |
public UserParcel[] newArray(int size) { | |
return new UserParcel[size]; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Important Note
Each subclass needs a
static final Parcelable.Creator
calledCREATOR
, otherwise Parcelable will not work. See the exampleUserParcel.java
for a basic usage.