【发布时间】:2013-01-12 00:15:58
【问题描述】:
我在我的一项活动中有一个文件,我会写入它(类似于日志文件)。我想将它传递给另一个活动并附加一些其他信息。我该怎么做? 我听说过 Parcelable 对象,但我不知道这是否是正确的解决方案。
【问题讨论】:
-
另一种解决方案是扩展 Application 类。 stackoverflow.com/questions/4572338/…
我在我的一项活动中有一个文件,我会写入它(类似于日志文件)。我想将它传递给另一个活动并附加一些其他信息。我该怎么做? 我听说过 Parcelable 对象,但我不知道这是否是正确的解决方案。
【问题讨论】:
在 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 也是另一种选择。
【讨论】: