2

I'm trying to make an Android app that will store widgets (represented as Views) in a database, and then be able to recreate them later on.

Here is the gist of it:

public class DBSerializer<T extends View & Serializable> {

public int storeWidget(T widget) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bytes);
    out.writeObject(widget);
    byte[] data = bytes.toByteArray();
    bytes.close();
    out.close();
    <store "data" in database>;
    return <unique database id>;
}

public T getWidget(int id) {
    byte[] data = <get data from database for the given id>;
    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data));
    return (T)in.readObject();
}

}

Unfortunately, the in.readObject() throws an InvalidClassException with the message android.view.View; IllegalAccessException.

Since Android's View directly extends Object, and Object has a no-argument constructor, shouldn't this work? Or is it trying to call View with a no-argument constructor? The error message is not being very clear about what the exact cause of the exception is.

Does anyone know what is causing this and how to fix it?

Dasmowenator
  • 5,505
  • 5
  • 36
  • 50

1 Answers1

7

Just because the base class has a parameterless constructor, that does not mean that subclasses will. TextView does not, nor do most other views.

Serializing a View in its entirety and retrieving it later doesn't seem like a good idea, since a View has a context, which may have been destroyed in the time between you commit the serialized version and the time your retrieve it.

Perhaps you could store only the data you need in a Parcel, and use that to get a byte array, which you could then store in your database as a blob. Chances are, you might find this approach useful anyways in conjunction with the onSaveInstanceState() method.

wsanville
  • 37,158
  • 8
  • 76
  • 101