简体   繁体   中英

Android - Parcelable | putParcelableArrayListExtra("ListItems", listItems);

I am trying to pass an ArrayList of objects MyItem from one activity to another. From what i understand i need to implement Parcable in MyItem class. So this is what i'va done so far:

public class MyItem implements ClusterItem, Parcelable {
    private LatLng mPosition=null;
    private String aString;

    public MyItem(double lat, double lng, String aString) {
        mPosition = new LatLng(lat, lng);
        this.aString= aString;
    }

    @Override
    public LatLng getPosition() {
        return mPosition;
    }

    public String getString(){
        return aString;
    }


    public int describeContents() {
        return 0;
    }


    public void writeToParcel(Parcel dest, int flags) {
        //dest.writeLngLat ?
        dest.writeString(postID);
    }

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

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

    private MyItem(Parcel in) {
        //mPosition = in.readLngLat ?
        aString = in.readString();
    }
}

First question : How could i write LngLat field in writeToParcel and how could i decleare it in MyItem(Parcel in) constructor?

Second question : Is this going to be enough so this piece of code could work?

                    ArrayList<MyItem> listItems = new ArrayList<>();
                    Iterator<MyItem> items = cluster.getItems().iterator();
                    while (items.hasNext()) {
                        listItems.add(items.next());
                    }
                    Intent intent = new Intent(MapsActivity.this, ClusterPosts.class);
                    intent.putParcelableArrayListExtra("oO", listItems);
                    startActivity(intent);

and then in CluserPosts:

    Intent intent = getIntent();
    ArrayList<MyItem> post = intent.getParcelableArrayListExtra("oO");
    for(MyItem item : post){
        Log.d("elaela", item.getString());
    }

Write parcel as -

dest.writeDouble(mPosition.latitude);
dest.writeDouble(mPosition.longitude);

You can write latitude and longitude as doubles only to the destination and then form a position.

dest.writeDouble(lat);
dest.writeDouble(long);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM