【问题标题】:Arraylist in parcelable object可打包对象中的数组列表
【发布时间】:2011-06-09 22:30:18
【问题描述】:

到目前为止,我已经看到了许多可打包的示例,但由于某种原因,当它变得更复杂时,我无法让它工作。 我有一个实现 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();
   }

}

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

提前致谢 卫斯理

【问题讨论】:

    标签: java android arraylist parcelable typed


    【解决方案1】:

    reviewsauthors 都为空。您应该首先初始化 ArrayList。一种方法是链接构造函数:

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

    【讨论】:

    • 非常感谢 MUUUUUCH,我在这上面浪费了 2 天时间 :-)。
    【解决方案2】:

    来自readTypedList 的 javadocs:

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

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

    你写的很简单

    dest.writeList(reviews);
    

    【讨论】:

    • 糟糕,我在复制粘贴我的代码之前更改了它。在我的项目中,我输入了这个,但感谢您注意到它!
    • 非常感谢!为我节省了很多时间
    • @NickT : dest.writeList 用于字符串、int、boolean 等类型的列表??
    • 最佳答案,位置在读写对象中很重要,我浪费了很多时间。但你的回答拯救了我的一天。谢谢兄弟。
    猜你喜欢
    • 2023-03-30
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多