Francesco Galgani
Francesco Galgani

Reputation: 6249

Save List of PropertyBusinessObjects to the Storage

I need to save a dinamic List of PropertyBusinessObjects to the Storage, but I didn't find how to do that. I should be able to add and remove items from the list.

The following test code throws java.io.IOException: Object type not supported: CollectiveDAO. I use registerExternalizable().

public class TestSaveListDAOs {

    private Form current;
    private Resources theme;
    public static List<CollectiveDAO> collectivesDB = new ArrayList<>();

    public void init(Object context) {
        [...]       
    }

    public void start() {
        if(current != null){
            current.show();
            return;
        }
        Form hi = new Form("Hi World", BoxLayout.y());
        hi.add(new Label("Hi World"));
        hi.show();

        restoreDB();
        collectivesDB.add(new CollectiveDAO());
        collectivesDB.add(new CollectiveDAO());
        saveDB();
        restoreDB();

    }

    public void stop() {
        [...]
    }

    public void destroy() {
    }

    public static void saveDB() {

        for (CollectiveDAO collectiveDAO : collectivesDB) {
            collectiveDAO.getPropertyIndex().registerExternalizable();
        }

        Storage.getInstance().writeObject("CollectivesDB", collectivesDB);
    }

    private static void restoreDB() {

        Object restoredCollectivesDB = Storage.getInstance().readObject("CollectivesDB");
        if (restoredCollectivesDB != null) {
            collectivesDB = ((List) restoredCollectivesDB);
        } 
    }

}
public class CollectiveDAO implements PropertyBusinessObject {

    public final Property<String, CollectiveDAO> collectiveID = new Property<>("collectiveID");

    private final PropertyIndex idx = new PropertyIndex(this, "CollectiveDAO",
            collectiveID);

    @Override
    public PropertyIndex getPropertyIndex() {
        return idx;
    }

}

Upvotes: 1

Views: 36

Answers (1)

Shai Almog
Shai Almog

Reputation: 52770

I'd use JSON rather than Externalizable such as:

public static void saveDB() {
    PropertyIndex.storeJSONList("CollectivesDB", collectivesDB);
}

private static void restoreDB() {
    collectivesDB = new CollectiveDAO().getPropertyIndex().loadJSONList("CollectivesDB");
}

It's shorter with nicer output. However, if you want to use Externalizable your usage is incorrect. You should remove the for call and instead do:

public void init(Object context) {
    new CollectiveDAO().getPropertyIndex().registerExternalizable();
    [...]       
}

This is needed only once for reading and writing (it was missing for reading). As it registers the new object type (CollectiveDAO).

Upvotes: 1

Related Questions