Skip to content

Instantly share code, notes, and snippets.

@czyrux
Created February 15, 2015 12:20
Show Gist options
  • Save czyrux/ccb845d8885e1dc70fa1 to your computer and use it in GitHub Desktop.
Save czyrux/ccb845d8885e1dc70fa1 to your computer and use it in GitHub Desktop.
Utility class for parceling objects in Android
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Utility class for parceling objects
*/
public class ParcelUtils {
private ParcelUtils() {
}
public static void writeBooleanToParcel(Parcel dest, boolean value) {
dest.writeByte((byte) (value ? 1 : 0)); // value == true, byte == 1
}
public static boolean readBooleanFromParcel(Parcel in) {
return in.readByte() != 0; // value == true if byte != 0
}
public static <T extends Parcelable> List<T> readParcelableArrayAsInmutableList(Parcel in, Class<T> clazz) {
Parcelable[] parcels = in.readParcelableArray(clazz.getClassLoader());
return ParcelUtils.readParcelableArrayAsInmutableList(parcels, clazz);
}
public static <T extends Parcelable> List<T> readParcelableArrayAsList(Parcel in, Class<T> clazz) {
Parcelable[] parcels = in.readParcelableArray(clazz.getClassLoader());
return ParcelUtils.readParcelableArrayAsList(parcels, clazz);
}
@SuppressWarnings("unchecked")
private static <T extends Parcelable> List<T> readParcelableArrayAsInmutableList(Parcelable[] parcels, Class<T> clazz) {
List<T> list = null;
if (parcels != null && parcels.length > 0) {
list = (List<T>) Arrays.asList(parcels);
}
return list;
}
@SuppressWarnings("unchecked")
private static <T extends Parcelable> List<T> readParcelableArrayAsList(Parcelable[] parcels, Class<T> clazz) {
List<T> list = null;
if (parcels != null && parcels.length > 0) {
list = new ArrayList<T>(parcels.length);
for (int i = 0; i < parcels.length; i++) {
list.add((T) parcels[i]);
}
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment