Reputation: 3450
I want to convert this generic class to a parcelable object, but I don't have very clear the concepts of the issue.
Class:
public class Type<T> implements Parcelable {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
This is what I've tried,. but I know that this is not correct, or maybe this is not complete.
public class Type<T> implements Parcelable {
// T stands for "Type"
private T t;
protected Type(Parcel in) {
}
public void set(T t) { this.t = t; }
public T get() { return t; }
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
}
public static final Creator< Type > CREATOR = new Creator< Type >() {
@Override
public Type createFromParcel(Parcel in) {
return new Type(in);
}
@Override
public Type[] newArray(int size) {
return new Type[size];
}
};
}
Upvotes: 0
Views: 1398
Reputation: 11018
Your generic data type may cause runtime error
so make sure you implements Parcelable and also the class you are passing should implement Parcelable otherwise it will cause runtime error.
public class Type<T extends Parcelable> implements Parcelable {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
protected Type(Parcel in) {
final String className = in.readString();
try {
t = in.readParcelable(Class.forName(className).getClassLoader());
} catch (ClassNotFoundException e) {
Log.e("readParcelable", className, e);
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(t);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<Type> CREATOR = new Parcelable.Creator<Type>() {
@Override
public Type createFromParcel(Parcel in) {
return new Type(in);
}
@Override
public Type[] newArray(int size) {
return new Type[size];
}
};
}
Upvotes: 1
Reputation: 1648
This is similar approach as vikas kumar but guarantte that you can pass only Parcelable as T parameter so you avoid exception.
public class Type<T extends Parcelable> implements Parcelable {
private T t;
protected Type(Parcel in) {
t = (T) in.readValue(t.getClass().getClassLoader());
}
public static final Creator<Type> CREATOR = new Creator<Type>() {
@Override
public Type createFromParcel(Parcel in) {
return new Type(in);
}
@Override
public Type[] newArray(int size) {
return new Type[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(t);
}
}
Upvotes: 2