简体   繁体   中英

How to deserialize my object in Android after passing it using an intent?

I'm trying to use Serializable to pass an object from one activity to another using the following code:

final Event rowItem = (Event) getItem(position);
Intent intent = new Intent(context, DetailsActivity.class);
intent.putExtra("event", rowItem);
context.startActivity(intent);

This works fine (no errors), so on the other end I want to deserialize it again using:

Intent intent = getIntent();
Event event = (Event) intent.getSerializableExtra("event");

Unfortunately, this results in an error saying:

java.lang.ClassCastException: java.lang.String cannot be cast to com.mycomp.model.Event

This is the first time I use Serializable to pass an object, so I might do something really stupid. I wouldn't know what however.

Does anybody know what I might be doing wrong here? I'd be happy to share more code if needed..

[EDIT] Turns out I did use @SerializedName(value = "the_serialized_name") for every parameter, but I didn't use implements Serializable with the class name. Extremely stupid of me. But thanks for answering!

Apparently you get a String instead of a Serializable when calling

(Event) intent.getSerializableExtra("event");

So You could try to print this line to see what value is returned. That might help you figure out what the problem is.

Also, you should have a look at the Parcelable Class, which is a kind of Serializable designed just for android

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM