Search code examples
javaandroidandroid-intentandroid-bundle

How to send ArrayList<CustomClass>() through activities


I have this class:

public class FlightData implements Parcelable {
    private double x;
    private double y;
    private double time;

    FlightData(double x, double y, double time){
        this.x = x;
        this.y = y;
        this.time = time;
    }

    private FlightData(Parcel in) {
        x = in.readDouble();
        y = in.readDouble();
        time = in.readDouble();
    }


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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeDouble(x);
        dest.writeDouble(y);
        dest.writeDouble(time);
    }

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

        @Override
        public FlightData[] newArray(int size) {
            return new FlightData[size];
        }
    };

    ...
}

I try to put it into a bundle, then an intent. But I can't even retrieve it in the same activity (it throws null in the other activity, so I've tried to get it in the current - null too):

        List<FlightData> flightDataList = new ArrayList<>();
        //... arraylist gets filled in
        intent = new Intent(this, DatasheetActivity.class);
        bundle = new Bundle();
        bundle.putParcelableArrayList("FlightDataList", (ArrayList<? extends Parcelable>) flightDataList);
        intent.putExtra("Bundle", bundle);

        Log.d("ErrorCustom",Integer.toString(flightDataList.size()));
//Log.d("ErrorCustom",Integer.toString(intent.getExtras().getParcelableArrayList("FlightDataList").size())); //throws null error

        startActivity(intent);

I do want to send the ArrayList, because it gets filled in the current activity (with a progressbar).


Solution

  • Just use putParcelableArrayListExtra with your intent and don't use Bundle.

    Try this

    Intent intent = new Intent(this, DatasheetActivity.class);
    intent.putParcelableArrayListExtra("FlightDataList", flightDataList );
    startActivity(intent);
    

    In other activity

    Intent intent = getIntent();
        if (intent != null) {
            List<FlightData> flightDataList;
            flightDataList = intent.getParcelableArrayListExtra("FlightDataList");
    }