Skip to content

Instantly share code, notes, and snippets.

@eugene-krivobokov
Created September 22, 2014 20:30
Show Gist options
  • Save eugene-krivobokov/dfb287a804dd003ade1b to your computer and use it in GitHub Desktop.
Save eugene-krivobokov/dfb287a804dd003ade1b to your computer and use it in GitHub Desktop.
Parcelable inheritance
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout....);
if (savedInstanceState != null) {
mBaseEntity = savedInstanceState.getParcelable(KEY_BASE_ENTITY);
mChildEntity = savedInstanceState.getParcelable(KEY_CHILD_ENTITY);
Log.i(TAG, "restore from state: " + mBaseEntity);
Log.i(TAG, "restore from state: " + mChildEntity);
} else {
mBaseEntity = new BaseEntity();
mChildEntity = new ChildEntity();
mChildEntity.name = this.toString();
Log.i(TAG, "create entity: " + mBaseEntity);
Log.i(TAG, "create entity: " + mChildEntity);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
Log.v(TAG, "onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_BASE_ENTITY, mBaseEntity);
outState.putParcelable(KEY_CHILD_ENTITY, mChildEntity);
}
import android.os.Parcel;
import android.os.Parcelable;
public class BaseEntity implements Parcelable {
public static final Parcelable.Creator<BaseEntity> CREATOR
= new Parcelable.Creator<BaseEntity>() {
public BaseEntity createFromParcel(Parcel in) {
return new BaseEntity(in);
}
public BaseEntity[] newArray(int size) {
return new BaseEntity[size];
}
};
protected String name = "name";
public BaseEntity() {
}
public BaseEntity(Parcel in) {
name = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
}
@Override
public String toString() {
return "BaseEntity [" + name + "]";
}
}
import android.os.Parcel;
import android.os.Parcelable;
public class ChildEntity extends BaseEntity {
public static final Parcelable.Creator<ChildEntity> CREATOR
= new Parcelable.Creator<ChildEntity>() {
public ChildEntity createFromParcel(Parcel in) {
return new ChildEntity(in);
}
public ChildEntity[] newArray(int size) {
return new ChildEntity[size];
}
};
protected String title = "title";
public ChildEntity(Parcel in) {
super(in);
title = in.readString();
}
public ChildEntity() {
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(title);
}
@Override
public String toString() {
return "ChildEntity{" +
"title='" + title + '\'' +
"} " + super.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment