【问题标题】:How to write to Parcel a List of Serializable (not Parcelable)如何向 Parcel 写入 Serializable(不可 Parcelable)列表
【发布时间】:2016-01-03 04:09:50
【问题描述】:

我正在使用具有 LatLong 对象的 mapsforge 库来存储地图上的点。不幸的是它只实现了 Serializable 接口,而不是 Parcelable。

public class LatLong implements Comparable<LatLong>, Serializable

在我的应用程序中,我有一个对象(我们称之为结果),其中存储了 LatLong 点的列表:

List<LatLong> points;

我的类 Result 实现了 Parcelable。

我的问题是如何写入 Parcel 一个列表,其中 LatLong 是可序列化的但不是 Parcelable? writeSerializable,writeTypedList 不工作。

【问题讨论】:

    标签: android parcelable serializable parcel


    【解决方案1】:

    在您的 writeToParcel() 方法中,使用以下代码:

    dest.writeInt(latLongList.size());
    for (LatLong latLong : latLongList) {
      dest.writeDouble(latLong.latitude);
      dest.writeDouble(latLong.longitude);
    }
    

    在从CREATOR.createFromParcel(Parcel source) 调用的私有对象构造函数中,使用以下代码:

    latLongList = new ArrayList<LatLong>();
    int size = source.readInt();
    for (int i = 0; i < size; i++) {
      double lat = source.readDouble();
      double lon = source.readDouble();
      latLongList.add(new LatLong(lat, lon));
    }
    

    这是基于我在 mapsforge.org 找到的 JavaDocs

    【讨论】:

    • 谢谢,它正在工作。另一种解决方案是使用 parcel.writeValue
    猜你喜欢
    • 2011-08-27
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 2012-03-12
    • 2012-03-08
    • 2019-01-11
    • 2018-01-04
    • 2019-04-26
    相关资源
    最近更新 更多