Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 651
Rohith Nandakumar Avatar asked Nov 10 '10 06:11

Rohith Nandakumar


1 Answers

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<ParcelableGeoPoint> CREATOR
             = new Parcelable.Creator<ParcelableGeoPoint>() {
         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<ParcelableGeoPoint> pointsExtra = new ArrayList<ParcelableGeoPoint>();
foreach(GeoPoint point: points) {
   pointsExtra.add(new ParcelableGeoPoint(point));
}
intent.putExtra("geopoints", pointsExtra);

3) in the called activity:

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

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

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

code should work, but is untested.

like image 194
Patrick Boos Avatar answered Sep 25 '22 22:09

Patrick Boos