Skip to content

Instantly share code, notes, and snippets.

@AaronRietschlin
Created March 31, 2015 22:01
Show Gist options
  • Save AaronRietschlin/666c04ca9ea46ffa64aa to your computer and use it in GitHub Desktop.
Save AaronRietschlin/666c04ca9ea46ffa64aa to your computer and use it in GitHub Desktop.
A simple way to use ArrayLists within Parcelable while keeping the array null if not present.
public class MyUtils {
private static final int PARCEL_LIST_NULL = 1151;
private static final int PARCEL_LIST_NOTNULL = 1152;
public static <T extends Parcelable> void appendListToParcel(Parcel out, @Nullable ArrayList<T> list) {
if (list == null) {
out.writeInt(PARCEL_LIST_NULL);
} else {
out.writeInt(PARCEL_LIST_NOTNULL);
out.writeList(list);
}
}
public static <T extends Parcelable> ArrayList<T> detachListFromParcel(Parcel in, ClassLoader cl) {
boolean isNull = in.readInt() == PARCEL_LIST_NULL;
if (!isNull) {
ArrayList<T> test = new ArrayList<>();
in.readList(test, cl);
return test;
}
return null;
}
}
public class MyClass implements Parcelable {
// "OtherClass" implements parcelable as well.
private ArrayList<OtherClass> list;
private MyClass(Parcel in) {
ArrayList<OtherClass> list = MyUtils.detachListFromParcel(in, OtherClass.class.getClassLoader());
if (test != null) {
topBadges = new ArrayList<>(test);
}
}
@Override
public void writeToParcel(Parcel dest, int flags) {
MyUtils.appendListToParcel(dest, list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment