【问题标题】:pass an object from one activity to another将对象从一个活动传递到另一个活动
【发布时间】:2013-01-12 00:15:58
【问题描述】:

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

【问题讨论】:

标签: android android-activity


【解决方案1】:

在 Appicaltion 类中存储变量是 NOT a good OOP concept。正如您已经提到的,通常由 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 本身就是 bad design,所以如果您没有遇到性能问题,实现 Serializable 也是另一种选择。

【讨论】:

  • 谢谢,也许我应该尝试这两种解决方案。
  • @wtsang02 没错。我的感觉是,真正的最佳 解决方案取决于需要存储的内容的生命周期、范围和性质。不过,问题中不包含详细信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 2018-10-10
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多