Skip to content

Instantly share code, notes, and snippets.

@rivancic
Created March 19, 2016 18:17
Show Gist options
  • Save rivancic/984bfce8e6964a3ffb12 to your computer and use it in GitHub Desktop.
Save rivancic/984bfce8e6964a3ffb12 to your computer and use it in GitHub Desktop.
Parcelable Model Wrapper
package com.zensound.parcelable;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
/**
* The Parcelable wrapper for Model that enables Model to be passed as an parameter to Activities
* or Fragments, or it can be stored in the SavedState.
*/
public final class ModelParcelable implements Parcelable {
public static final Creator<ModelParcelable> CREATOR
= new Creator<ModelParcelable>() { // NOSONAR
public ModelParcelable createFromParcel(Parcel in) {
return new ModelParcelable(in);
}
public ModelParcelable[] newArray(int size) {
return new ModelParcelable[size];
}
};
private final Model model;
private ModelParcelable(Parcel in) {
this.model = new Model();
model.setName(in.readString());
}
public ModelParcelable(Model model) {
this.model = model;
}
/**
* Handy method that is transforming a list of ModelParcelables to the list of Models.
*
* @param modelParcelableList the parcelable that is wrapping the Model.
* @return the list of un parceled Models.
*/
public static List<Model> getList(List<ModelParcelable> modelParcelableList) {
List<Model> list = null;
if (modelParcelableList != null) {
list = new ArrayList<>();
for (ModelParcelable modelParcelable : modelParcelableList) {
list.add(modelParcelable.getModel());
}
}
return list;
}
/**
* Handy method that is transforming a list of Models to the list of
* ModelParcelables.
*
* @param modelList the list of Models.
* @return the list of wrapped Models in parcel.
*/
public static ArrayList<ModelParcelable> getParcelableList(List<Model> modelList) {
ArrayList<ModelParcelable> list = null;
if (modelList != null) {
list = new ArrayList<>();
for (Model model : modelList) {
list.add(new ModelParcelable(model));
}
}
return list;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(model.getName());
}
public Model getModel() {
return this.model;
}
@Override
public int describeContents() {
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment