Hemmels
Hemmels

Reputation: 892

Android passing Bundle with primitive and Parcelable

I don't understand why I cannot Bundle both a Parcelable object and a primitive in the same Bundle. See below.

Bundle bundle = new Bundle();
bundle.putInt("num", 4); // I like 4.
bundle.putParcelable("myObject", myObject);
Intent localIntent = new Intent(SendingClass.this, ReceivingClass.class);
localIntent.putExtras(bundle);
startActivity(localIntent);

And my ReceivingClass' onCreate(Bundle savedInstanceState), (which i'm aware that the sIS is null here)...

Bundle bundle = getIntent().getExtras();
int num = bundle.getInt("num");
MyObject myObject = (MyObject) bundle.getParcelable("myObject");

I would have expected both num and myObject to contain something, however, myObject is populated, but num is always 0.

If I remove the putParcelable and getParcelable lines however, "num" is then correctly populated (with 4).

Looking at the bundle, it seems to only populate with a Parcelable object if it has one, and "drops" all other primitives. Why is this? I haven't been able to find documentation saying Bundles cannot contain both primitives and Parcelables, what gives?

P.S. I have tried to add both the primitive to the Bundle first, and after the Parcelable, but no dice either way.

Upvotes: 3

Views: 607

Answers (1)

Hemmels
Hemmels

Reputation: 892

As expected, it was due to an error in my Parcelable class.

If your public void writeToParcel(Parcel paramParcel, int paramInt){ method writes too many things for the "make object from Parcel' method public ParcelableClass(Parcel paramParcel) {, you will get strange errors in your log, this is what is causing the issue.

Make sure the read and write methods have the same number of read/writes, and of the correct data types.

In my case I was writing 4 objects, (2 Parcelable, 2 primitives), but only reading the 2 Parcelables, and 1 primitive. It just seems strange that some objects made it through ok.

Upvotes: 1

Related Questions