Saving my Serialized Class that have not serialized objects like Rect

1.2k views Asked by At

I'm trying to save my Serialized object when the activity calls the onDestroy() but when i try to write my object using ObjectOutputStream a java.io.NotSerializableExeption is thrown.

Can you please help me. Thanks

3

There are 3 answers

0
Niko On

I encountered same problem and made this class to help the serialization:

public class SerializableRect implements Serializable {

private static final long serialVersionUID = 1L;

private Rect mRect;

public SerializableRect(Rect rect) {
    mRect = rect;
}

public Rect getRect() {
    return mRect;
}

private void writeObject(java.io.ObjectOutputStream out) throws IOException {
    int left = mRect.left;
    int top = mRect.top;
    int right = mRect.right;
    int bottom = mRect.bottom;

    out.writeInt(left);
    out.writeInt(top);
    out.writeInt(right);
    out.writeInt(bottom);
}

private void readObject(java.io.ObjectInputStream in) throws IOException,
        ClassNotFoundException {
    int left = in.readInt();
    int top = in.readInt();
    int right = in.readInt();
    int bottom = in.readInt();

    mRect = new Rect(left, top, right, bottom);
}
}
0
Sinthia V On

If your object map contains an unserializable object the VM looks for a no argument constructor so as to make an object with the default values and move on. It throws this exception when it can't. The bottom line is that each and every object referenced in your object graph must either:

  1. Implements Serializable, (and all of it's members do too), or
  2. Inherits from a base class that implements Serializable(and all members follow the rules), or
  3. Implements Serializable and all unserializable members are marked as Volatile, or
  4. Unserializable members not so marked have a no-argument default constructor for use in deserialization.

You do not provide enough specifics for me to go further, but I can't write it for you anyway? In general, you can derive from the unserializable classes or wrap them and provide the necessary functionality. So long as each member meets the conditions I listed, no exception should be thrown.

2
Roman Nurik On

You need to ensure that the class implements the java.io.Serializable interface. Also consider using Bundles instead and saving your data in onSaveInstanceState. For more on data storage, see this dev guide topic.