【问题标题】:Android - Parcel: unable to marshal valueAndroid - Parcel:无法编组值
【发布时间】:2019-12-28 17:58:51
【问题描述】:

我正在尝试使用 Parcelable 通过活动传递数据。这是我的代码:

public class Player implements Parcelable {

public static final Parcelable.Creator<Player> CREATOR = new Parcelable.Creator<Player>() {
    public Player createFromParcel(Parcel in) {
        return new Player(in);
    }

    public Player[] newArray(int size) {
        return new Player[size];
    }
};
private String name;
private List<Card> listCards;

public Player(String namePlayer) {
    name = namePlayer;
    listCards = new ArrayList<>();
}

private Player(Parcel in) {
    // This order must match the order in writeToParcel()
    name = in.readString();
    in.readList(listCards, null);
    // Continue doing this for the rest of your member data
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(name);
    dest.writeList(listCards);
}

每当我运行此代码时,我都会收到错误消息:

java.lang.RuntimeException: Parcel: unable to marshal value com.antoinedelia.lebarbu_versionalcool.Card@ec54bb

你知道可能是什么问题吗?

谢谢

【问题讨论】:

  • 卡是一个单独的类?这是否实现Parcelable
  • Card 确实是一个单独的类,但它没有实现 Parcelable。

标签: android parcelable parcel


【解决方案1】:
@Override
public void writeToParcel(Parcel dest, int flags) {
  dest.writeString(name);
  dest.writeList(listCards);
}

由于Card 类没有实现Parcelable 你不能做writeList/readList。仅适用于Parcelable 对象列表。

【讨论】:

  • 它不仅适用于 Parcelable,只是如果它不是其他类型的 Object 可以被 Parcel-ed 则回退到写 Parcelable
  • @cricket_007 Serializable 也适用于writeToParcel ?
  • writeList 循环遍历所有对象并执行writeValue(Object) - 可以在此处找到列表developer.android.com/reference/android/os/…
猜你喜欢
  • 2016-11-04
  • 2014-08-13
  • 2016-10-15
  • 1970-01-01
  • 2012-03-12
  • 2013-09-28
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多