2015-10-07 30 views
-2

我有一个父类实现parcelable和子延伸的父母也实现parcelable。我的代码附在下面。我得到一个运行时ClassCastException。我错过了什么? 谢谢,在android引起的可转发继承导致ClassCastExeption

父类:

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]; 
      } 
     }; 

}

在服务器上,我创建了一个青少年/跟随像下面。青少年和追随者clasess被复制到服务器没有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; 
    } 

我相信这是一个小的,我失踪,但我在失去。任何帮助将不胜感激。谢谢,

+0

'Log.d''follower'然后看到logcat – pskink

+0

使用可序列化的 –

+0

@pskink,我得到了跟随者对象。 –

回答

0

更改此:

public class Teen extends Follower implements Parcelable{

这样:

public class Teen extends Follower{

你不必重新实现在孩子parcelable,因为它从父继承。我不确定,但是当您创建一个青少年时,它会实现它自己的可以分类的数据类型,并且它不是具有父类可分类数据类型的分层结构。

+0

谢谢,我改变了青少年班。但没有帮助。这只是示例代码。我需要这个青少年也是一名追随者。一旦它正常工作,我需要在它周围添加很多功能。 –

+0

这是错的。因为我的Json中也存在继承问题,所以IT没有工作。谢谢! –