Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement parcelable interface using Gson

I'm trying to implement the parcelable interface using Gson. The idea is to create a json string (using gson) and write it to the parcel object.

Could it be a correct way to implement the interface?

The only problem I've encountered is when I deserialize the object. Actually, I use gson to recreate the object.

private MyClass(Parcel in) {
    String json = in.readString();
    Gson gson = new Gson();
    gson.fromJson(json, getClass());
}

The problem is that the fromJson function returns an object that is the object the constructor should create. The last line of code should be something like

this=gson.fromJson(json, getClass());

So, if this is a correct way to implement Parcelable, how could I solve this problem?

like image 861
Daniele Vitali Avatar asked Oct 20 '22 20:10

Daniele Vitali


1 Answers

You should read more carefully the Parcelable javadoc. It contains everything you need.

As quoted in the docs :

Interface for classes whose instances can be written to and restored from a Parcel. Classes implementing the Parcelable interface must also have a static field called CREATOR, which is an object implementing the Parcelable.Creator interface.

So you should have the writeToParcel method declared and also use a creator that will produce instances of your class from a Parcel.

The private constructor is an additional helper that you can use to set the value of the fields of an object given a parcel, but not the object itself. In Java, this is a right value, and can't be assigned.

BTW, the goal of parcelisation is to be provide a short term fast serialization process. You should, generally speaking, use a fast and compact data format when you use parcelisation. JSON is not a candidate of choice, but it will work.

like image 59
Snicolas Avatar answered Oct 23 '22 11:10

Snicolas