Busca

Mark Vasconcelos Creative Solutions

Teaching & Learning

Categoria

Uncategorized

Simpliest way to implement android.os.Parcelable and Parcelable.Creator trought Json converter library / Maneira mais simples de implementar Parcelable no Android

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

Anúncios

2012 in review

Mesmo postando quase nada esse ano, as visitas foram constantes, continuarei com o trabalho agora que tenho tempo 🙂

 

The WordPress.com stats helper monkeys prepared a 2012 annual report for this blog.

Here’s an excerpt:

4,329 films were submitted to the 2012 Cannes Film Festival. This blog had 41,000 views in 2012. If each view were a film, this blog would power 9 Film Festivals

Click here to see the complete report.

Blog no WordPress.com.

Acima ↑