Parcelable Class implementation requiring context

I would like my data class to implement Parcelable, so it can be split between Activity, however it also needs a reference to Context so that the fields can be stored in SQLiteDatabase.

This, however, is a problem because the Parcelable.Creator createFromParcel method has only one Parcel parameter.

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 does a class that implements Parcelable also reference the context so that it is stored in SQLiteDatabase?

+6
source share
2 answers

The Parcelable interface is similar to the Java Serializable interface. Objects that implement this interface must be serialized. This means that it should be possible to convert the object to a view that can be saved in a file, for example.

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 illogical, since it can be, for example, Activity.

If you want to keep your activity status in the database, you must find another way to do this.

+5
source

Your write class probably doesn't really need access to the SQL database. The reason for this is precisely the problem that you are currently facing: it is very difficult to insert a Context into each record.

Perhaps the best solution would be to implement a static RecordSQLService that has a save(Record r) method. Your application can start RecordSQLService when the application starts, so it will remain alive as long as your application is running, and it takes responsibility for saving from the Record class, which makes it so that you no longer need Context, and he can package it.

0
source

Source: https://habr.com/ru/post/888925/


All Articles