35

到目前为止,我已经看到了许多可打包的示例,但由于某种原因,当它变得更复杂时,我无法让它工作。我有一个实现 Parcelable 的 Movie 对象。这本书对象包含一些属性,例如 ArrayLists。执行 ReadTypedList 时运行我的应用程序会导致 NullPointerException !我真的没有想法

public class Movie implements Parcelable{
   private int id;
   private List<Review> reviews
   private List<String> authors;

   public Movie () {
      reviews = new ArrayList<Review>();
      authors = new ArrayList<String>();
   }

   public Movie (Parcel in) {
      readFromParcel(in);
   }

   /* getters and setters excluded from code here */

   public void writeToParcel(Parcel dest, int flags) {

      dest.writeInt(id);
      dest.writeList(reviews);
      dest.writeStringList(authors);
   }

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

      public MoviecreateFromParcel(Parcel source) {
         return new Movie(source);
      }

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

   };

   /*
    * Constructor calls read to create object
    */
   private void readFromParcel(Parcel in) {
      this.id = in.readInt();
      in.readTypedList(reviews, Review.CREATOR); /* NULLPOINTER HERE */
      in.readStringList(authors);
   }
}

复习课:

    public class Review implements Parcelable {
   private int id;
   private String content;

   public Review() {

   }

   public Review(Parcel in) {
      readFromParcel(in);
   }

   public void writeToParcel(Parcel dest, int flags) {
      dest.writeInt(id);
      dest.writeString(content);
   }

   public static final Creator<Review> CREATOR = new Creator<Review>() {

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

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

   private void readFromParcel(Parcel in) {
      this.id = in.readInt();
      this.content = in.readString();
   }

}

如果有人能让我走上正确的轨道,我将不胜感激,我花了很多时间寻找这个!

提前感谢韦斯利

4

2 回答 2

38

reviews并且authors都是空的。您应该首先初始化 ArrayList。一种方法是链接构造函数:

public Movie (Parcel in) {
   this();
   readFromParcel(in); 
}
于 2011-01-16T10:13:40.137 回答
15

来自javadocs readTypedList

读入包含特定对象类型的给定列表项writeTypedList(List)

在当前dataPosition()。该列表必须先前已writeTypedList(List)使用相同的对象类型写入。

你用简单的方式写了它们

dest.writeList(reviews);
于 2011-01-16T10:18:48.770 回答