Skip to content

Instantly share code, notes, and snippets.

@moagrius
Last active August 26, 2016 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moagrius/91ee45103466185d86ca26a400da220c to your computer and use it in GitHub Desktop.
Save moagrius/91ee45103466185d86ca26a400da220c to your computer and use it in GitHub Desktop.

so a MediaCollection (or any ContentCollection) has a List.
The ContentElement interface will have a save method, that takes some reference to a database or database helper, and the implementation will take care of saving:

void Chapter.save(Database db) {
  Values values = new Values();
  // populate values with information
  db.insertOrUpdate(CHAPTERS_TABLE).values(values);
}
...
void MediaCollection.save(Database db) {
  for(ContentElement contentElement : contentElements ) {
    contentElement.save(db);
  }
}

That's fairly straightforward, but reading out is not - need to know what table to query, and what id's for that table. Subathra had the idea to maintain a map table:

create table MAP_TABLE (collectionId int, table enum/varchar, referenceId int)
List<ContentElement> MedaiCollection.getElementsFromDb() {
  List<ContentElement> contentElements = new ArrayList<>();
  Cursor cursor = db.select(MAP_TABLE).where("id", getId()).findAll();
  while(cursor.hasNext()){
    String table = cursor.getColumn(1);
    int referenceId = cursor.getColumn(2);
    Cursor elementCursor = db.select(table).where("id", referenceId).findFirst();
    Class<? extends ContentElement> clazz = Class.forName(table);
    ContentElement contentElement = clazz.newInstance();
    contentElement.read(elementCursor);
    contentElements.add(contentElement);
  }
  return contentElements;
}

Which means the save operation now how to save to the mapping table as well...

void MediaCollection.save() {
  Database db = getDb();
  for(ContentElement contentElement : contentElements ) {
    contentElement.save(db);
    db.insert(MAP_TABLE).values(collectionId, contentELement.getClass(), contentElement.getIdentifier());
  }
}

This is all very similar to what Subathra had; the real difference is that we don't have to maintain lists in memory, just in the database.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment