SQLDelight in Android: Getting Started

Aug 3 2021 · Kotlin 1.4, Android 11, Android Studio 4.1

Part 1: Preparation & Setup

06. Add Functions to Tables

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 05. Understand SQLDelight's Type System Next episode: 07. Use Grouping Statements

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

We have covered the creation of tables and columns, but so far we haven’t actually used the database for something substantial - you know, like inserting or fetching data. Well, no more I say! Let’s add some functionality to the sample app.

all:
SELECT * FROM collection;
fun listCollections(): Query<Collection> {
    return database.collectionQueries.all()
}
private val collectionQuery = repository.listCollections()
private fun refreshState() {
    _state.value = State.Result(
        collections = collectionQuery.executeAsList()
    )
}
private val collectionQuery = repository.listCollections()

+private val collectionQueryListener = object : Query.Listener {
+    override fun queryResultsChanged() {
+        refreshState()
+    }
+}

init {
    refreshState()

+    collectionQuery.addListener(collectionQueryListener)
}

+override fun onCleared() {
+    collectionQuery.removeListener(collectionQueryListener)
+}
insert:
INSERT INTO collection(creationTime, name)
VALUES (:creationTime, :name);
fun addCollection(name: String) {
    database.collectionQueries.insert(
        creationTime = ZonedDateTime.now().withZoneSameInstant(UTC),
        name = name
    )
}
fun addCollection(name: String) {
    repository.addCollection(name)
}