2012-09-16 60 views
1

我正在使用Android應用程序,並且正在嘗試使用Parcelable傳遞信息。所以這就是我所擁有的。Android Parcelable無法實例化類型

import android.os.Parcel; 
import android.os.Parcelable; 

abstract class Role implements Parcelable { 

    private String name; 
    private String image; 

    public Role() { 

    } 

    public Role(Parcel read) { 
     name = read.readString(); 
     image = read.readString(); 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getImage() { 
     return image; 
    } 

    public void setImage(String image) { 
     this.image = image; 
    } 

    public String toString() { 
     return this.name; 
    } 

    public static final Parcelable.Creator<Role> CREATOR = 
      new Parcelable.Creator<Role>() { 

       public Role createFromParcel(Parcel source) { 
        return new Role(source); 
       } 

       public Role[] newArray(int size) { 
        return new Role[size]; 
       } 
      }; 

    public int describeContents() { 
     // TODO Auto-generated method stub 
     return 0; 
    } 

    public void writeToParcel(Parcel dest, int flags) { 
     // TODO Auto-generated method stub 
     dest.writeString(name); 
     dest.writeString(image); 
    } 

} 

然而,當我嘗試編譯我的錯誤(其中我把評論)

無法實例的類型角色

對這個有什麼想法?

問候

回答

1

我沒有用在抽象類自己parcelable,但它應該是好的。您可能要檢查here或者更一般here

我有一個非常相似的類(兩個字符串),但它是一個公共靜態類。 我在構造函數中的字符串成員上執行new()。

+0

*捂臉*對不起我沒有意識到,我必須管理從它那裏單獨繼承的類,但它只有這樣纔有意義 – brancz

1

Yout類Role定義爲abstract,抽象類不能被實例化。

只是定義你的類角色:

class Role implements Parcelable { 
    //... 
} 
1

正如qjuanp提到的,一個不能實例abstract類(按照Java的共同OOP定義;您不能範例的東西是抽象的,它已得到更定義)。

我敢肯定你正在嘗試使用角色的某些子類(也就是你可以同時使用abstract並在這裏實現Parcelable的唯一途徑),可以考慮使用此approach

public abstract class A implements Parcelable { 
    private int a; 

    protected A(int a) { 
     this.a = a; 
    } 

    public void writeToParcel(Parcel out, int flags) { 
     out.writeInt(a); 
    } 

    protected A(Parcel in) { 
     a = in.readInt(); 
    } 
} 

public class B extends A { 
    private int b; 

    public B(int a, int b) { 
     super(a); 
     this.b = b; 
    } 

    public static final Parcelable.Creator<B> CREATOR = new Parcelable.Creator<B>() { 
     public B createFromParcel(Parcel in) { 
      return new B(in); 
     } 

     public B[] newArray(int size) { 
      return new B[size]; 
     } 
    }; 

    public int describeContents() { 
     return 0; 
    } 

    public void writeToParcel(Parcel out, int flags) { 
     super.writeToParcel(out, flags); 
     out.writeInt(b); 
    } 

    private B(Parcel in) { 
     super(in); 
     b = in.readInt(); 
    } 
}