到目前为止,我已经看到许多可拆分的示例,但是由于某种原因,当它变得更加复杂时,我无法使其正常工作。我有一个Movie对象,该对象实现了Parcelable。本书对象包含一些属性,例如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(); } }
如果有人能让我走上正确的道路,我将不胜感激,我已经花了很多时间寻找这个!
感谢韦斯利
reviews并且authors均为null。您应该首先初始化ArrayList。一种方法是链接构造函数:
reviews
authors
public Movie (Parcel in) { this(); readFromParcel(in); }