【发布时间】:2015-10-07 06:51:39
【问题描述】:
我有一个实现 Parcelable 的父类和一个子扩展父类也实现了 Parcelable。我的代码附在下面。我得到一个运行时 ClassCastException。我错过了什么? 谢谢,
父类:
public class Follower implements Parcelable{
private long id;
private String fullName;
public Follower() {
}
public Follower(String fullName) {
this.fullName = fullName;
}
public long getId(){
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getFullName());
}
protected Follower(Parcel in){
setFullName(in.readString());
}
public static final Parcelable.Creator<Follower> CREATOR =
new Parcelable.Creator<Follower>() {
public Follower createFromParcel(Parcel in) {
return new Follower(in);
}
public Teen[] newArray(int size) {
return new Teen[size];
}
};
}
子类
public class Teen extends Follower
implements Parcelable{
public Teen(){
super();
}
public Teen( String fullName, String birthDate) {
super(fullName);
this.birthDate = birthDate;
}
private String birthDate;
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate){
this.birthDate = birthDate;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString (birthDate);
}
private Teen(Parcel in){
super(in);
birthDate = in.readString();
}
public static final Parcelable.Creator<Teen> CREATOR =
new Parcelable.Creator<Teen>() {
public Teen createFromParcel(Parcel in) {
return new Teen(in);
}
public Teen[] newArray(int size) {
return new Teen[size];
}
};
}
在服务器上,我创建了一个青少年/关注者,如下所示。 teen 和 follower 类在没有 parcelable 实现的情况下被复制到服务器。
public Follower getData()
{
if (logic to see if the user is a teen){
Teen t = new Teen( "Full Name", "1:1:1960");
return t;
}
else
{
Follower f = new Follower("Full Name");
return f;
}
}
在客户端
我确实在客户端代码中获得了关注者。我已经通过访问 Follower 类方法进行了检查。有用。但是,当我做这样的事情时,我会在运行时收到 ClassCastException。
if(logic to see if it is a teen)
{
Teen t = (Teen) follower;
}
我确信这是我想念但不知所措的小事。任何帮助将不胜感激。谢谢,
【问题讨论】:
-
Log.dfollower然后看看logcat -
@pskink,我正在获取关注者对象。
-
@AnandSavjani,是的,如果 parcelable 不起作用,我必须回退到可序列化但在 android 上出于速度原因试图使用 parcelable。谢谢,
-
那么如何将
Follower转换为Teen?不可能……你的"logic to see if it is a teen"坏了 -
Serializable 是 parcelable 的替代品。但是当你在 bean 中使用时,如果你使用 Serializable 就更好了。
标签: android inheritance classcastexception parcelable