5

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

4

1 回答 1

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

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

于 2013-01-28T16:02:19.707 回答