我有这个课:

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];
        }
    };

    ...
}


我尝试将其打包,然后是意图。但是我什至无法在同一个活动中检索它(它在另一个活动中抛出null,所以我也尝试在当前活动中获取它-null):

        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);


我确实要发送ArrayList,因为它被填充在当前活动中(带有进度条)。

最佳答案

仅出于意图使用putParcelableArrayListExtra,不要使用Bundle。

尝试这个

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


在其他活动中

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

关于java - 如何通过 Activity 发送ArrayList <CustomClass>(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58283332/

10-09 07:35