首页 > 解决方案 > 如何使 GEO Point Class Parcelable 或 Serializable 因为我想使用 Intent 传递它们

问题描述

我使用 Cloud Firestore 作为我的数据库,并且在每个文档中都有一个名为 restaurant_info 的地图,它通常存储 <"name","Name of the Restaurant">、<"Location",GEOPoint of the Restaurant> 等等字段。问题是 Geo Point 类没有实现 Parcelable 或 Serializable 接口。

标签: androidfirebasegoogle-cloud-firestoreparcelable

解决方案


有两种方法可以解决这个问题。第一个是添加到Restaurant实现Parcelable接口的类中:

class Restaurant implements Parcelable {}

然后覆盖writeToParcel()方法并创建另一个构造函数,如下所示:

private GeoPoint geoPoint;

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeDouble(geoPoint.getLatitude());
    parcel.writeDouble(geoPoint.getLongitude());
}

public Restaurant(Parcel in) {
    Double lat = in.readDouble();
    Double lng = in.readDouble();
    geoPoint = new GeoPoint(lat, lng);
}

第二种方法是将latand存储long在你的Restaurant类中作为双原语,每次你需要一个 GeoPoint 对象时,像这样创建它:

GeoPoint geoPoint = new GeoPoint(restaurant.getLatitude(), restaurant.getLongitudeE6());

推荐阅读