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.
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];
}
};
}
How can a class that implements Parcelable also reference Context so it save to SQLiteDatabase?
Create Parcelable class without plugin in Android Studioimplements Parcelable in your class and then put cursor on "implements Parcelable" and hit Alt+Enter and select Add Parcelable implementation (see image). that's it.
The Parcelable interface adds methods to all classes you want to be able to transfer between activities. These methods are how parcelable deconstructs the object in one activity and reconstructs it in another.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With