The Room Mechanics

The PackagedFTS module of the book’s primary sample project is a clone of the FTS module, except that we now switch to using a packaged database.

In the original FTS project, we had assets/TheTimeMachine/ as a directory, containing a series of text files representing chapters in the book. Now, we have assets/TheTimeMachine.db, a SQLite database containing our paragraphs. We will discuss later in the chapter where this database came from. For the moment, assume that it was created using a magnetized needle and a steady hand.

When our BookDatabase newInstance() function uses Room.databaseBuilder() to set up the database, we have an extra configuration call: createFromAsset(). This provides a relative path within assets/ to the database that we want to use at the outset:

package com.commonsware.room.fts

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

private const val DB_NAME = "book.db"

@Database(
  entities = [ParagraphEntity::class, ParagraphFtsEntity::class],
  version = 1
)
abstract class BookDatabase : RoomDatabase() {
  abstract fun bookStore(): BookStore

  companion object {
    fun newInstance(context: Context) =
      Room.databaseBuilder(context, BookDatabase::class.java, DB_NAME)
        .createFromAsset("TheTimeMachine.db")
        .build()
  }
}

For simple cases, that is all that we need.

In particular, BookRepository no longer needs all that code that we had to import the text files. We can just have pass-through calls to the database:

package com.commonsware.room.fts

class BookRepository(private val db: BookDatabase) {
  suspend fun all() = db.bookStore().all()

  suspend fun filtered(search: String): List<String> =
    db.bookStore().filtered(search)
}

Everything else works as it did before, and if you run the app, it should behave as does the original.

(Why did the FTS module bother with the whole import-the-text-files approach? That chapter, and its sample app, were written before createFromAsset() was added to Room.)


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.