gpt4 book ai didi

android - 实现包含其他 Parcelable 的 Parcelable 时出现问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:01:12 29 4
gpt4 key购买 nike

我正在实现具有另一个 Parcelable insde 的 Parcelable 类。

在 OuterParcelable 类中:

@Override
public void writeToParcel(Parcel dest, int flags) {
Bundle tmp = new Bundle();

tmp.putParcelable("innerParcelable", mParcelable);
dest.writeBundle(tmp);

然后:

public OuterParcelable(Parcel parcel) {
super();

Bundle b = parcel.readBundle();
mParcelable = b.getParcelable("innerParcelable");

和:

    public OuterParcelable createFromParcel(Parcel in) {
return new OuterParcelable(in);
}

当我使用上面的代码重新创建对象时,我得到:

 08-18 17:13:08.566: ERROR/AndroidRuntime(15520): Caused by: android.os.BadParcelableException: ClassNotFoundException when unmarshalling: my.package.InnerParcelable

最佳答案

一种将非原始属性存储为可分割的、可能为空的值的简洁方法。使用 Parcel.writeValue()readValue() .请参阅下面代码中的注释:

public class MyParcelableClass implements Parcelable {
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(getIntegerAttribute()); // getIntegerAttribute() returns Integer
dest.writeValue(getDoubleAttribute());
dest.writeValue(getMyEnumAttribute()); // getMyEnumAttribute() returns a user defined enum
dest.wrtieValue(getUserClassAttribute()); //UserClass must implement Parcelable in a similar fashion
}

private MyParcelableClass(Parcel in) {
setIntegerAttribute((Integer)in.readValue(null)); //pass null to use default class loader. Ok for Integer, String, etc.
setDoubleAttribute((Double)in.readValue(null)); //Cast to your specific attribute type
setEnumAttribute((MyEnum)in.readValue(null));
setUserClassAttribute((UserClass)in.readValue(UserClass.class.getClassLoader())); //Use specific class loader
}

@Override
public int describeContents() ...

public static final Parcelable.Creator<ParcelableLocationBean> CREATOR ...
}

像魅力一样工作。 writeValue() 和 readValue() 封装了可能的空值处理和类型检测。来自 javadoc:

public final void writeValue (Object v)
Flatten a generic object in to a parcel. The given Object value may currently be one of the following types:
null, String, Integer, ...
String[], boolean[], ...
Any object that implements the Parcelable protocol. ...

关于android - 实现包含其他 Parcelable 的 Parcelable 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3513665/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com