Last active
August 29, 2015 14:00
-
-
Save nseidm1/11399613 to your computer and use it in GitHub Desktop.
Generic serializable and parcelable collection container with auto cast support
This file contains hidden or 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
package com.serve.platform.service.support; | |
import java.io.Serializable; | |
import java.util.Arrays; | |
import java.util.LinkedList; | |
import android.os.Parcel; | |
import android.os.Parcelable; | |
public class Extras implements Parcelable { | |
private static final int PARCELABLE = 0; | |
private static final int SERIALIZABLE = 1; | |
private LinkedList<Item> mItems = new LinkedList<Item>(); | |
public static Extras createExtras(Item... items) { | |
return new Extras(items); | |
} | |
private Extras(Item... items) { | |
mItems = new LinkedList<Item>(Arrays.asList(items)); | |
} | |
public Extras(Parcel in) { | |
do { | |
int type = in.readInt(); | |
switch(type) { | |
case PARCELABLE: | |
mItems.add((Item) in.readParcelable(null)); | |
break; | |
case SERIALIZABLE: | |
mItems.add((Item) in.readSerializable()); | |
break; | |
} | |
} while (in.dataPosition() < in.dataSize()); | |
} | |
public <T> T get(int position) { | |
Item item = mItems.get(position); | |
return cast(item.mItem); | |
} | |
@SuppressWarnings("unchecked") | |
private static <TSource, TTarget> TTarget cast(TSource toCast){ | |
return (TTarget) toCast; | |
} | |
public int size() { | |
return mItems.size(); | |
} | |
public static class Item { | |
public Object mItem; | |
public static Item create(Object item) { | |
return new Item(item); | |
} | |
private Item(Object item) { | |
mItem = item; | |
} | |
} | |
@Override | |
public int describeContents() { | |
// TODO Auto-generated method stub | |
return 0; | |
} | |
@Override | |
public void writeToParcel(Parcel dest, int flags) { | |
for (Item item : mItems) { | |
if (item.mItem instanceof Parcelable) { | |
dest.writeInt(PARCELABLE); | |
dest.writeParcelable((Parcelable) item.mItem, 0); | |
} else if (item.mItem instanceof Serializable) { | |
dest.writeInt(SERIALIZABLE); | |
dest.writeSerializable((Serializable) item.mItem); | |
} | |
} | |
} | |
public static final Parcelable.Creator<Extras> CREATOR = new Parcelable.Creator<Extras>() { | |
@Override | |
public Extras createFromParcel(Parcel in) { | |
return new Extras(in); | |
} | |
@Override | |
public Extras[] newArray(int size) { | |
return new Extras[size]; | |
} | |
}; | |
public static class ResultPayload extends Extras{} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment