可分辨对象中的Arraylist

Wes*_*ley 33 java android arraylist typed parcelable

到目前为止,我已经看到了许多可以说明的例子,但由于某种原因,当它变得有点复杂时,我无法让它工作.我有一个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);
   }
}
Run Code Online (Sandbox Code Playgroud)

评论课:

    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();
   }

}
Run Code Online (Sandbox Code Playgroud)

如果有人能让我走上正轨,我会非常感激,我花了很多时间寻找这个!

谢谢Wesley先生

Mat*_*hen 37

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

public Movie (Parcel in) {
   this();
   readFromParcel(in); 
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*ckT 15

从javadocs readTypedList:

读入包含使用特定对象类型编写的给定List项 writeTypedList(List)

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

你用简单的方式写了它们

dest.writeList(reviews);
Run Code Online (Sandbox Code Playgroud)