Caros, segue solução mais simples possível que encontrei para implementar Parcelable no Android (Obs.: Post em inglês).
I recently found a simple solution to implement the android.os.Parcelable interface (and Creator) on Android trought the usage of Gson library API.
The solution is to write one string and read one string from the Parcels at writeToParcel/readFromParcel with the results from Gson.toJson and Gson.fromJson
The resulted code doesn’t requires methods reading every item from parcels, and the model class doesnt need constructors too.
A sample is implemented in the following model:
class User { long id; String login; String pass; /** * @param dest * Writes String Gson.toJson(this) into 'dest' */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(new Gson().toJson(this)); } public transient static final Parcelable.Creator<User> CREATOR = new Creator<User>() { /** * @param source * @return read string from 'source' as Gson */ @Override public User createFromParcel(Parcel source) { return new Gson().fromJson(source.readString(), User.class); } @Override public User[] newArray(int size) { return new User[size]; }}; @Override public int describeContents() { return 0; } }
PS: Sorry the try of making the relevants part of code clearly by this formatation.
😉
[]’s
janeiro 18, 2017 at 2:19 pm
Hey Mark, did you test performance? Likely this conversion is costly.
janeiro 18, 2017 at 2:24 pm
I did not, the cost of Gson is the same as Reflection, for hot-VM without lookup it is about 10ms (on first run is 100ms, compared to 10ms native).