简体   繁体   中英

ClassNotFoundException when deserializing Serializable object through Intent from Android

I have two Android Application A and B. For the App A. I have a Serializable Object

public class MyObject implements Serializable {
public String[] var1;
public ArrayList<Integer> var2;

public MyObject (String[] var1, ArrayList<Integer> var2) {
    this.var1= var1;
    this.var2= var2;
}

Then, I send the instance of this class through Intent to another activity in App B by using

Intent i= new Intent("appB.component");
i.putExtra("myobject", fc);
startActivity(i);

In App B, I create the same Serializable class in App A. I try to get this but I got java.lang.RuntimeException: Parcelable encountered ClassNotFoundException reading a Serializable object (name = appA.MyObject )

Bundle b = getIntent().getExtras();               
MyObject o = (MyObject) b.getSerializable("myobject");

Do we have a way to change the reference of the class in app A to app B, or manual way to parsing this object while do not modify the code in app A.

Well appA.MyObject and appB.MyObject are not the same class. One can't be deserialized into the other.

You would be better of to use GSON or a library like it to serialize your appA.MyObject class to JSON, send the resulting String through the Intent, and then deserialize the JSON String back to the appB.MyObject class.

Alternatively you could try to give both appA.MyObject and appB.MyObject a

private static final long serialVersionUID

field and set both UIDs to the same value. But I am not sure if that works.

A word of advice from the Android Serializable documentation :

Implement Serializable Judiciously

Refer to Effective Java's chapter on serialization for thorough coverage of the serialization API. The book explains how to use this interface without harming your application's maintainability.

Recommended Alternatives

JSON is concise, human-readable and efficient. Android includes both a streaming API and a tree API to read and write JSON. Use a binding library like GSON to read and write Java objects directly.

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