将对象从一个活动传递到另一个活动

Mar*_*ria 5 android android-activity

我在我的一个活动中有一个文件,我写它(类似于日志文件).我想将它传递给另一个活动,并附加一些其他信息.我该怎么做?我听说过Parcelable对象,但我不知道这是否是正确的解决方案.

wts*_*g02 1

在 Appicaltion 类中存储变量不是一个好的 OOP 概念。正如您已经提到的,通常由 Parcelable 完成,这是模型类实现它的示例:

    public class NumberEntry implements Parcelable {

        private int key;
        private int timesOccured;
        private double appearRate;
        private double forecastValue;

        public NumberEntry() {

            key = 0;
            timesOccured = 0;
            appearRate = 0;
            forecastValue = 0;
        }
    public static final Parcelable.Creator<NumberEntry> CREATOR = new Parcelable.Creator<NumberEntry>() {
            public NumberEntry createFromParcel(Parcel in) {
                return new NumberEntry(in);
            }

            public NumberEntry[] newArray(int size) {
                return new NumberEntry[size];
            }
        };
/**
     * private constructor called by Parcelable interface.
     */
    private NumberEntry(Parcel in) {
        this.key = in.readInt();
        this.timesOccured = in.readInt();
        this.appearRate = in.readDouble();
        this.forecastValue = in.readDouble();
    }

    /**
     * Pointless method. Really.
     */
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.key);
        dest.writeInt(this.timesOccured);
        dest.writeDouble(this.appearRate);
        dest.writeDouble(this.forecastValue);
    }
Run Code Online (Sandbox Code Playgroud)

然而,正如其他人所说,Parcelable 本身就是一个糟糕的设计,因此如果您没有遇到性能问题,实现 Serialized 也是另一种选择。