我刚刚开发了我的第一个 Parcelable 类,它实现了 Parcelable 接口。我真的很高兴,因为它工作正常。也许我的解决方案可以帮助任何人:
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];
}
};
}
我将 Object Parcelable“DealCategory”从活动 A 发送(写入)到活动 B
protected void returnParams(DealCategory dc) {
Intent intent = new Intent();
intent.putExtra("Category", dc);
setResult(REQUEST_CODE_LISTA_DEALS, intent);
finish()
}
我从活动 A 接收(读取)活动 B 中的 Object Parcelable“DealCategory”
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle b = data.getExtras();
DealCategory dc = (DealCategory) b.getParcelable("Category");
我检查我是否收到更正的值。我暂时在日志中显示它们
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