可打包对象中的数组列表

2022-09-01 06:48:07

到目前为止,我已经看到了很多可包裹的例子,但由于某种原因,当它变得更加复杂时,我无法让它工作。我有一个 Movie 对象,它实现了 Parcelable。此 book 对象包含一些属性,如 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();
   }

}

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

感谢卫斯理


答案 1

reviews并且两者都为空。您应该首先初始化 ArrayList。执行此操作的一种方法是链接构造函数:authors

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

答案 2

从 javadocs for :readTypedList

读入包含特定对象类型的给定 List 项,这些对象项是用writeTypedList(List)

在当前 .该列表以前必须使用相同的对象类型通过编写。dataPosition()writeTypedList(List)

你用一个平原写了他们

dest.writeList(reviews);

推荐