实现需要上下文的可包裹类 [英] Implementing Parcelable Class That Requires Context
问题描述
我想让我的数据类实现Parcelable,以便可以在Activity之间共享它,但是它也需要引用Context,以便可以将字段保存到SQLiteDatabase.
I'd like for my data class to implement Parcelable so it can be shared between Activities, however it also needs reference to Context so the fields can be saved to SQLiteDatabase.
但是,这是一个问题,因为Parcelable.Creator方法createFromParcel仅具有一个参数Parcel.
This however is a problem since Parcelable.Creator method createFromParcel only has one parameter Parcel.
public abstract class Record implements Parcelable {
protected Context context;
protected String value;
public Record(Context context) {
this.context = context;
}
public Record(Parcel parcel) {
this.value = parcel.readString();
}
public void save() {
//save to SQLiteDatabase which requires Context
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flag) {
parcel.writeString(value);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Record createFromParcel(Parcel parcel) {
return new Record(in);
}
public Record[] newArray(int size) {
return new Record[size];
}
};
}
实现Parcelable的类还如何引用Context,以便将其保存到SQLiteDatabase?
How can a class that implements Parcelable also reference Context so it save to SQLiteDatabase?
推荐答案
The Parcelable interface is like the Java interface Serializable. Objects which implement this interface should be serializable. This means it should be possible to transform the object to a representation which could be saved in a file e.g.
很容易使用字符串,int,float或double等,因为它们都具有字符串表示形式.Context类显然不可序列化和不可打包,因为例如它可以是一个Activity.
It is easily possible for a string, int, float or double etc, because they all have a string representation. The Context class is clearly not serializable and not parcelable, because it can be an Activity for example.
如果要将活动状态保存到数据库中,则应该找到另一种方法.
If you want to save the state of your activity to a database, you should find another way to do that.
这篇关于实现需要上下文的可包裹类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!