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

5

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


1
https://dev59.com/H1bUa4cB1Zd3GeqPBsbU?rq=1 - R3D3vil
另一种解决方案是扩展Application类。https://dev59.com/6G455IYBdhLWcg3wCfmC - StarsSky
1个回答

1
在应用程序类中存储变量不是一个好的面向对象编程概念。通常使用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);
    }

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


谢谢,也许我应该尝试两种解决方案。 - Maria
@wtsang02 没错。我的感觉是,真正“最好”的解决方案取决于需要存储的内容的生命周期、范围和性质。然而,这些细节并没有包含在问题中。 - class stacker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接