I am trying to pass array of customized object using Parcelable. I found some discussions in my search like link. I followed these examples and but can't find the implementation for the array of objects. My problem is object becomes null at the new activity. My implementation is as follow.
MY percelable object
public class showStatisticsObj implements Parcelable{
public String dt = null;
public int totalmiles = 0;
public Date date = null;
public showStatisticsObj() { ; };
public showStatisticsObj(Parcel in) { readFromParcel(in); }
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
// TODO Auto-generated method stub
arg0.writeString(dt);
arg0.writeInt(totalmiles);
}
public void readFromParcel(Parcel in) {
dt = in.readString();
totalmiles = in.readInt();
}
@SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public showStatisticsObj createFromParcel(Parcel in)
{
return new showStatisticsObj(in);
}
public showStatisticsObj[] newArray(int size)
{
return new showStatisticsObj[size];
}
};
}
Parcelable[] passedArray = new Parcelable[totaldifferentDates];
for (int i=0; i<totaldifferentDates; ++i) {
passedArray[i] = showStatObj[i];
}
Intent displayintent = new Intent(this, DisplayStatistics.class);
displayintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
displayintent.putExtra("bundleObj", passedArray);
startActivity(displayintent);
At the new activity, I extract as
Bundle bundle = getIntent().getExtras();
showStatObjinDisplay = (showStatisticsObj) bundle.getParcelable("bundleObj");
But showStatObjinDisplay is null. What is wrong?Pls help me.
I would try change CREATOR like Minhtdh said.
Next you don't need following code, because you already have parcelable array (showStatisticsObj is Parcelable):
// you don't need following code
Parcelable[] passedArray = new Parcelable[totaldifferentDates];
for (int i=0; i<totaldifferentDates; ++i) {
passedArray[i] = showStatObj[i];
}
So you just pass showStatObj to intent:
Intent displayintent = new Intent(this, DisplayStatistics.class);
displayintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
displayintent.putExtra("bundleObj", showStatObj);
startActivity(displayintent);
And finally you get it from bundle like this:
Parcelable[] ps = bundle.getParcelableArrayExtra();
showStatisticsObj[] uri = new showStatisticsObj[ps.length];
System.arraycopy(ps, 0, uri, 0, ps.length);
You passed Parcelable[] so have to search for Parcelable[] in bundle and then convert it to showStatisticsObj[]. In java you can't cast Parcelable[] to showStatisticsObj[].
And as suggestion for you code, class names should always start with uppercase letter. So not showStatisticsObj, but ShowStatisticsObj.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With