Android - Problem with the Serializable interface

2019-05-20 04:24发布

问题:

I have been using the Serializable interface to pass an object from one activity to another. I am using putExtra on the sender side and getSerializable on the receiver side. Everything works fine but I have received (for the first time) the following error report:

java.lang.RuntimeException: Parcelable encountered IOException reading a Serializable object

I don't understand why this exception has been generated since I am using getSerializable and not getParcelable.

I know that I should implement the Parcelable interface instead because it has been designed specifically for Android (and that's what I will end up doing) but I want to understand why I am getting this error.

Thanks!

回答1:

Parcelable is mentioned in this error because an Intent you send from one Activity to another has a Bundle inside and this Bundle is Parcelable. When you call Intent.putExtra() this extra is added to the inner Bundle. When Intent is passed between activities its Bundle is converted to and from a byte array and so is your Serializable object.

But I don't know why this error occurs. Maybe it's because of some bug in writeObject()/readObject() implementation.