CRUD operations are operations for creating, updating, selecting, or removing data. They are defined with an interface called Crud and it will be generic. Create a new interface in the database package. Make sure it covers all CRUD operations:
interface Crud<T> where T : DbModel { companion object { val BROADCAST_ACTION = "com.journaler.broadcast.crud" val BROADCAST_EXTRAS_KEY_CRUD_OPERATION_RESULT = "crud_result" } /** * Returns the ID of inserted item. */ fun insert(what: T): Long /** * Returns the list of inserted IDs. */ fun insert(what: Collection<T>): List<Long> /** * Returns the number of updated items. */ fun update(what: T): Int /** * Returns the number of updated items. */ fun update(what: Collection<T>): Int /** * Returns the number of deleted items. */ fun delete(what: T): Int /** * Returns the number of deleted items. */ fun delete(what: Collection<T>): Int /** * Returns the list of items. */ fun select(args: Pair<String, String>): List<T> /** * Returns the list of items. */ fun select(args: Collection<Pair<String, String>>): List<T> /** * Returns the list of items. */ fun selectAll(): List<T> }
For executing CRUD operations, there are two method versions. First version is the one that accepts collections of instances and the second that accepts a single item. Let's create CRUD concretization by creating a Kotlin object called Db. Creating an object makes our concretization a perfect singleton. The Db object must implement the Crud interface:
package com.journaler.database import android.content.ContentValues import android.location.Location import android.util.Log import com.journaler.model.Note import com.journaler.model.Todo object Db { private val tag = "Db" private val version = 1 private val name = "students" val NOTE = object : Crud<Note> { // Crud implementations } val TODO = object : Crud<NoteTodo { // Crud implementations } }