Best practice to update my data structure?

I have the following problem and need a best practice to solve it:

I have a App with a List of data of Type Foo. This list (ArrayList<Foo>) I save to the file system with:

FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);

When I start the App I load it with:

FileInputStream fis = context.openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
MyList = (ArrayList<Foo>) ois.readObject();

Now my problem: I want to extend the Foo class with some additional attributes. The problem is, that a user has the old list saved and want to load it into the new Foo class, the app will crash.

What is a a best practice to solve this update problem?


Using Serialization in your scenario may not be the best pick. To avoid the crash you can use serialVersionUID to distinguish betweeen different versions of the same class.

From the Java API:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.

If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender’s class, then deserialization will result in an InvalidClassException.

A serializable class can declare its own serialVersionUID explicitly by declaring a field named serialVersionUID that must be static, final, and of type long.

Is your data model so complex that it can’t be written in SQLite DB? This will allow you to handle the load of the model selectively, skipping null attributes that may result loading a new model with an older structure.

Leave a Reply

Your email address will not be published. Required fields are marked *