Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Parcelable Class That Requires Context

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?

like image 963
Dale Zak Avatar asked May 24 '11 15:05

Dale Zak


People also ask

How do you implement Parcelable?

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.

What is a primary purpose of the Parcelable interface?

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.


1 Answers

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.

like image 97
Franziskus Karsunke Avatar answered Sep 21 '22 01:09

Franziskus Karsunke