Passing an array of objects between two activities

时间:2019-03-19 15:16:09

标签: java android

I have an array Workout with each element being an instance of class Exercise. The MainActivity has a 'start' button which passes control to a StartExercise activity, which displays the first instance of Exercise in the Workout array.

When the exercise has been completed, the StartExercise activity calls a Rest activity which has a one minute countdown timer.

At the end of that minute, the Rest activity 'finishes' returning control to the StartExercise activity where the next exercise in the Workout array is displayed.

I would like some advice about the best way to pass the Workout and Exercise objects between these activities. If I initialise the Workout array in the StartActivity I would have to make sure that was only done once. Which seems clumsy.

Any suggestions?

2 个答案:

答案 0 :(得分:1)

您的自定义类必须实现Parcelable接口。 Parcelable的典型实现是:

 public class MyParcelable implements Parcelable {
    private int mData;

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

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

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

    private MyParcelable(Parcel in) {
        mData = in.readInt();
    }
}

然后您可以使用以下方式发送数据:

Intent intent;
intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putParcelableArrayListExtra("Workout", workout);
startActivity(intent);

并收到:

workout = getIntent().getParcelableArrayListExtra("Workout");

注意:确保主自定义类的每个嵌套类都实现了Serializable接口

答案 1 :(得分:0)

使用可拆分接口实现+ Oleg提供的intent方法是实现此目的的好方法。

另一种方法是使用Singleton设计模式并将共享数据存储在该Singleton对象中。