OGeek|极客世界-中国程序员成长平台

标题: Android: Pass List<GeoPoint> to another Activity [打印本页]

作者: 菜鸟教程小白    时间: 2022-5-28 10:47
标题: Android: Pass List<GeoPoint> to another Activity

I have an ArrayList of type GeoPoint.

private List<GeoPoint> points = new ArrayList<GeoPoint>();

I want to pass points to another Activity and retrive the data in that activity. How do I do it? I know I have to use the parcelable but I searched, but could not find a way to pass ArrayLists.



Best Answer-推荐答案


This function will help you: http://developer.android.com/reference/android/content/Intent.html#putParcelableArrayListExtra(java.lang.String, java.util.ArrayList<? extends android.os.Parcelable>)

But the problem is, that GeoPoint is not Parcelable. Well, you can do a workaround here:

1) Create a class, that implements Parcelable:

public class ParcelableGeoPoint implements Parcelable {

     private GeoPoint geoPoint;

     public ParcelableGeoPoint(GeoPoint point) {
          geoPoint = point;
     }

     public GeoPoint getGeoPoint() {
          return geoPoint;
     }

     public int describeContents() {
         return 0;
     }

     public void writeToParcel(Parcel out, int flags) {
         out.writeInt(geoPoint.getLatitudeE6());
         out.writeInt(geoPoint.getLongitudeE6());
     }

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

         public ParcelableGeoPoint[] newArray(int size) {
             return new ParcelableGeoPoint[size];
         }
     };

     private ParcelableGeoPoint(Parcel in) {
         int lat = in.readInt();
         int lon = in.readInt();
         geoPoint = new GeoPoint(lat, lon);
     }
 }

2) when sending to the other activity (points is your List<GeoPoint>:

ArrayList<arcelableGeoPoint> pointsExtra = new ArrayList<arcelableGeoPoint>();
foreach(GeoPoint point: points) {
   pointsExtra.add(new ParcelableGeoPoint(point));
}
intent.putExtra("geopoints", pointsExtra);

3) in the called activity:

ArrayList<arcelableGeoPoint> pointsExtra =  getIntent().getParcelableArrayListExtra("geopoints");

ArrayList<GeoPoint> points = new ArrayList<GeoPoint>();

foreach(ParcelableGeoPoint point: pointsExtra) {
   points.add(point.getGeoPoint());
}

code should work, but is untested.






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://www.ogeek.cn/) Powered by Discuz! X3.4