- Learn how to include a pre-built database in an Android mobile application with Kotlin
- Create an Index and validate the database will work for future steps
はじめに
In this part of the learning path, you will be working with the “Audit Inventory” demo app that allows users to log in and access the developer screens in order to validate the use of a pre-build database in the demo application that is used to store warehouse and stock item documents. The warehouse and stock item documents will be used in future steps of the learning path when we need to add projects and audits to the database.
In this step of the learning path you will learn the fundamentals of:
- Including a prebuilt database in an Android mobile application
- Preparing the prebuilt database for use
- Creating an Index
- Validating the database works for future steps
アプリの概要
デモアプリには多くの機能がありますが、このステップでは以下について説明します。
- アプリケーションにログインする
- 開発者画面へのアクセス
- Accessing the Developer – Database Information screen
- Reviewing the Logcat logs
- Reviewing the files on the emulator using Device File Explorer

インストール
アプリのソースコードを取得する
ソースコードの複製
- If you haven’t already cloned the repo from the previous step, clone the
コットナブ・ライトの Kotlin と Jetpack Compose を活用して学ぶGitHubからのリポジトリ。.
git clone https://github.com/couchbase-examples/android-kotlin-cbl-learning-path.git
試してみてください
- Android Studioを使用して src/build.gradleを開きます。.
- プロジェクトのビルドと実行を行います。.
- 表示されていることを確認してください
データベースにアイテムが見つかりませんでした。プロジェクト画面のメッセージ。.

データモデル
Couchbase Lite は JSON ドキュメントストアであるという点に注意してください。 文書 名前付きフィールドと値の論理的な集合です。値は任意の有効な JSON 型です。標準の JSON 型に加え、Couchbase Lite は 日付 そして ブロブ データ型。必須ではありませんが、推奨される慣行として、 “「type」” 関連するドキュメントの命名空間として機能するプロパティ。.
The Warehouse Document
The sample app comes bundled with a collection of 文書 with a “「documentType」” 財産の所有者 “「倉庫」”. Each document represents an warehouse location that a team would visit in order to perform an audit of the inventory at that location.
文書の例としては、以下のようなものがあります:
{
"warehouseId":"e1839e0b-57a0-472c-b29d-8d57e256ef32",
"name":"Santa Clara Warehouse",
"address1":"3250 Dr Olcott Street",
"address2":"",
"city":"Santa Clara",
"state":"CA",
"postalCode":"95054",
"salesTax":0.0913,
"latitude":32.3803024,
"longitude":-121.9674197,
"documentType":"warehouse",
"yearToDateBalance":0,
"shippingTo": [
"AZ",
"CA",
"HI",
"NV"
],
}
The Warehouse Data Class
もしある人が “「倉庫」” is retreived from the database it is stored within an Data Class of type Warehouse.
data class Warehouse(
val warehouseId: String,
val name: String,
val address1: String,
val address2: String? = "",
val city: String,
val state: String,
val postalCode: String,
val salesTax: Double,
val yearToDateBalance: Double,
val latitude: Double,
val longitude: Double,
val documentType: String,
val shippingTo: List<String>,
)
The Item Document
The sample app comes bundled with a collection of 文書 with a “「documentType」” 財産の所有者 “「アイテム」”. Each document represents an item in stock that a team would count in order to perform an audit of the inventory in the warehouse.
文書の例としては、以下のようなものがあります:
{
"itemId":"00b66fdf-9bdb-451b-bd2a-75bdf0459958",
"name":"Bachensteiner Beard Export",
"price":24.22,
"description":"Tranquil Export with Bachensteiner flavors",
"style": "Imperial Stout",
"documentType":"item"
}
StockItem データクラス
もしある人が “「アイテム」” is retreived from the database it is stored within an Data Class of type StockItem.
データクラス StockItem (
itemId:文字列「itemId」は、「商品ID」です。「itemId」は商品IDの文字列です。
var name: 文字列 = "",
var price: Float,
var description:文字列 = "",
var style: 文字列 = "",
var documentType: String = "item")
Using a Prebuilt Database
There are several reasons why you may want to bundle your app with a prebuilt database. This would be suited for data that does not change or change that often, so you can avoid the bandwidth and latency involved in fetching/syncing this data from a remote server. This also improves the overall user experience by reducing the start-up time.
In our app, the instance of Couchbase Lite that holds the pre-loaded “warehouse” and “stockItem” data is separate from the Couchbase Lite instance that holds “user”, “project”, and “audit” data. A separate Couchbase Lite instance is not required. However, in our case, since there can be many users potentially using the app on a given device, it makes more sense to keep it separate. This is to avoid duplication of pre-loaded data for every user and to help speed up the app vs pulling down the warehoue and items when the app is first installed.
Location of the cblite file
The pre-built database will be in the form of a cblite file. It should be in your app project bundle
- In the startinglocations.zip file within the Assets folder.

注: The cblite folder will be extracted from the zip file.
Loading the Prebuilt Database
- 開く DatabaseManager.kt ファイルを選択して、
initializeDatabases()function. The prebuilt database is common to all users of the app (on the device). So it will be loaded once and shared by all users on the device. Note that the currentUser is required to setup the inventory database for use which holds the user profile documents, as covered in the Key Value step of the learning path.
fun initializeDatabases(currentUser: User)
- First, we create an instance of the
DatabaseConfigurationobject and specify the path where the database would be located
val dbConfig = DatabaseConfigurationFactory.create(context.filesDir.toString())
- Then we determine if the “warehouse” database already exists at the specified location. It would not be present if this is the first time we are using the app, in which case, we locate the “startingWarehouses.zip” resource in the App’s main bundle, unzip it, and then we copy it over to the Database folder.
If the database is already present at the specified Database location, we simply open the database.
private fun setupWarehouseDatabase(dbConfig: DatabaseConfiguration) {
// create the warehouse database if it doesn't already exist
if (!Database.exists(warehouseDatabaseName, context.filesDir)) {
unzip(startingWarehouseFileName, File(context.filesDir.toString()))
// copy the warehouse database to the project database
// never open the database directly as this will cause issues
// with sync
val warehouseDbFile =
File(
String.format(
"%s/%s",
context.filesDir,
("${startingWarehouseDatabaseName}.cblite2")
)
)
Database.copy(warehouseDbFile, warehouseDatabaseName, dbConfig)
}
warehouseDatabase = Database(warehouseDatabaseName, dbConfig)
}
Note: You MUST copy the pre-built database using the Database.copy function instead of opening it directly or you will run into issues with data syncronization.
Indexing the Database
-
Creating indexes for non-FTS based queries is optional. However, to speed up queries, you can create indexes on the properties that you would query against. Indexes can slow down writes, so it’s recommended adding indexes as you need them. Indexing is handled eagerly.
-
In the DatabaseManager.kt ファイルを見つけ、
createTypeIndex(database: Database?)関数です。. -
We create an index on the
documentTypeproperty of the documents in the database that is referenced to the function using the databases createIndex function. The createIndex function requires the name of the index along with the expression of what to index.
private fun createTypeIndex(
database: Database?
) {
// create index for document type if it doesn't exist
database?.let {
if (!it.indexes.contains(typeIndexName)) {
it.createIndex(
typeIndexName, IndexBuilder.valueIndex(
ValueIndexItem.expression(
Expression.property(typeAttributeName))
)
)
}
}
}
Note: Since both databases have documents that use a
documentTypeproperty, it was easier to create a function that could be used to create the index for either database. ThetypeIndexNameそしてtypeAttributeNamevariables are defined at the top of the DatabaseManager class.
Closing the Database
When a user logs out, we close the pre-built database along with other user-specific databases
-
In the DatabaseManager.kt ファイルを見つけ、
closeDatabases()関数です。. -
Closing the databases is pretty straightforward
fun closeDatabases() {
try {
inventoryDatabase?.close()
warehouseDatabase?.close()
} catch (e: java.lang.Exception) {
android.util.Log.e(e.message, e.stackTraceToString())
}
}
試してみてください
- このアプリはエミュレータで実行されている必要があります。.
- 任意のメールアドレスとパスワードでアプリにログインしてください。以下の値を利用しましょう。 “demo@example.com“ そして “「P@ssw0rd12」” それぞれユーザー ID フィールドとパスワード フィールドです。これが初めてこの設定を行う場合、 何でも ユーザーがアプリにログインすると、プリビルドされたデータベースがアプリバンドルから読み込まれます。さらに、チーム固有の新しいデータベースが作成/開かれます。.
- Confirm that the console log output has a message similar to the one below. This output also indicates the location of the pre-built database as well as the inventory database. In this example, we are logging in with a user email Id of “demo@example.com“.
I/CouchbaseLite/DATABASE: Copying prebuilt database from
/data/data/com.couchbase.kotlin.learningpath/files/startingWarehouses.cblite2/
to /data/user/0/com.couchbase.kotlin.learningpath/files/warehouse.cblite2
- The above log message indicates the location of the pre-built database as well as the Database for the inventory data. This would be within the files folder.
- Open the folder on your computer and verify that a Database with name “「倉庫」” exists along with a team specific Database with name “teamname_inventory” where teamname is the name of the team the user is assigned to

- Click the Drawer menu icon (sometimes referred to the Hamburger icon) and tap on Developer
- Tap on the Database Information button
- Validate the Location Database Path, Warehouse Database Name, and Warehouse Count which should be 50
- Validate that the Stock Item Count is 3000

さらに詳しく
私たちの学習のこのステップを完了してくれてありがとう!
This step of the learning path walked you through an example of how to use a pre-built Couchbase Lite database. Check out the following links for further documenation and continue on to the next step that covers how to insert documents into the database using Batch operations.
参考文献