how to put and get intent of parcelable array list

2019-09-19 15:48发布

问题:

i try to send this zaznam Arraylist from one activity to second and it wont works..

first activity

ArrayList<LatLng> zaznam = new ArrayList<LatLng>();
zaznam.add(new LatLng(66,55));
zaznam.add(new LatLng(44,77));
zaznam.add(new LatLng(11,99));

Intent intent2 = new Intent(TrackerActivity.this, MakacMapa.class);
intent2.putParcelableArrayListExtra("Zaznam",zaznam);

Second activity

Intent intent = new Intent();
ArrayList<LatLng> zaznam = intent.getParcelableArrayListExtra("Zaznam");  //and here it throws NullPointerExeption :/

回答1:

you are not passing the array list as parcelable. You need to customize the model (LatLong) used to implement Parcelable. Try the below code.

LatLong.java

public class LatLong implements Parcelable {

int lat, long;

public int LatLong (int lat, int long) {
this.lat = lat;
this.long = long;
}


public int setLat(int lat) {
this.lat = lat;
}
public int getLat() {
return lat;
}
public int setLong(int long) {
this.long = long;
}

public int getLong() {
return long;
}
       @Override
       public int describeContents() {
       return 0;
       }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(lat);
        dest.writeInt(long);
        }


        public static final Creator<LatLong> CREATOR = new Creator<LatLong>() {
         @Override
         public LatLong createFromParcel(Parcel source) {
         return new LatLong(source);
         }

         @Override
         public LatLong[] newArray(int size) {
         return new LatLong[size];
       }
     };
}// LatLong Ends

Activity1.java

ArrayList<LatLng> zaznam = new ArrayList<LatLng>();
zaznam.add(new LatLng(66,55));
zaznam.add(new LatLng(44,77));
zaznam.add(new LatLng(11,99));

Below code is important. Passing the list as Parcelable.

Intent intent2 = new Intent(TrackerActivity.this, MakacMapa.class);
intent2.putParcelableArrayListExtra("Zaznam", (ArrayList<? extends Parcelable>) zaznam);

Activity2.java

Intent intent = new Intent();
ArrayList<LatLng> zaznam = getIntent().getParcelableArrayListExtra("Zaznam");

Hope this will help you.. !! comment me if you have any query.