I just developed my first Parcelable class which implements the interface Parcelable.
I am really happy because it works correctly.
Maybe my solution can help anyone:
public class DealCategory implements Parcelable {
private int categoryID;
private String categoryName;
private List<DealCategory> listaCategoriasSeleccionadas = new ArrayList<DealCategory>();
/**
* GET/SET
*/
//-----------------------------------------------------------|
//-----------------------------------------------------------|
//------------------- METHODS FOR PARCELABLE ----------------|
//-----------------------------------------------------------|
//-----------------------------------------------------------|
/*
* (non-Javadoc)
* @see android.os.Parcelable#describeContents()
* Implementacion de los metodos de la Interfaz Parcelable
*/
@Override
public int describeContents() {
return hashCode();
}
/*
* (non-Javadoc)
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
* IMPORTANT
* We have to use the same order both TO WRITE and TO READ
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(categoryID);
dest.writeString(categoryName);
dest.writeTypedList(listaCategoriasSeleccionadas);
}
/*
* (non-Javadoc)
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
* IMPORTANT
* We have to use the same order both TO WRITE and TO READ
*
* We reconstruct the object reading from the Parcel data
*/
public DealCategory(Parcel p) {
categoryID = p.readInt();
categoryName = p.readString();
p.readTypedList(listaCategoriasSeleccionadas, DealCategory.CREATOR);
}
/*
* (non-Javadoc)
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
* We need to add a Creator
*/
public static final Parcelable.Creator<DealCategory> CREATOR = new Parcelable.Creator<DealCategory>() {
@Override
public DealCategory createFromParcel(Parcel parcel) {
return new DealCategory(parcel);
}
@Override
public DealCategory[] newArray(int size) {
return new DealCategory[size];
}
};
}
I send(write) the Object Parcelable "DealCategory" from Activity A to Activity B
protected void returnParams(DealCategory dc) {
Intent intent = new Intent();
intent.putExtra("Category", dc);
setResult(REQUEST_CODE_LISTA_DEALS, intent);
finish()
}
I receive(read) the Object Parcelable "DealCategory" in Activity B from Activity A
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle b = data.getExtras();
DealCategory dc = (DealCategory) b.getParcelable("Category");
I check if I receive corrected values. I temporaly show them in log
for (int i = 0; i < dc.getListaCategorias().size(); i++) {
Log.d("Selected Category", "ID: " + dc.getListaCategorias().get(i).getCategoryID() + " -- NAME:" + dc.getListaCategorias().get(i).getCategoryName());
lR += dc.getListaCategorias().get(i).getCategoryName() +", ";
}
} //Close onActivityResult