- Learn how to run Couchbase Lite in Standalone mode.
- Use the Key Value engine to create and update documents.
はじめに
In this part of our learning path, you will walk through the “Audit Inventory” demo application of using Couchbase Lite in standalone mode, which means the database does not sync information from other resources using replication. While the demo app has a lot of functionality, this step will walk you through:
- Installing Couchbase Lite on Android
- Database operations for creating, opening, closing, and deleting a database
- Document create, read, update, and delete (CRUD) operations via key-value pair
In this step of the learning path, you will be working with the code that allows users to log in and make changes to their user profile information. User profile information is persisted as a 文書 in the local Couchbase Lite データベース. When the user logs out and logs back in again, the profile information is loaded from the データベース.

インストール
アプリのソースコードを取得する
ソースコードの複製
- Clone the
コットナブ・ライトの Kotlin と Jetpack Compose を活用して学ぶGitHubからのリポジトリ。.
git clone https://github.com/couchbase-examples/android-kotlin-cbl-learning-path.git
Installing Couchbase Lite Framework
- The Demo app already contains the appropriate additions for downloading and utilizing the Kotlin Android Couchbase Lite dependency module. However, in the future, to include Couchbase Lite support within an Andorid app add the following within src/build.gradle
allprojects {
repositories {
...
maven {
url "https://mobile.maven.couchbase.com/maven2/dev/"
}
}
}
Then add the following to the app/build.gradle ファイル。.
dependencies {
...
implementation "com.couchbase.lite:couchbase-lite-android-ktx:3.0.0"
}
試してみてください
- Android Studioを使用して src/build.gradleを開きます。.
- プロジェクトのビルドと実行を行います。.
- ログイン画面が表示されていることを確認してください。.

データモデル
Couchbase Lite は JSON ドキュメントストアです。 文書 名前付きフィールドと値の論理的な集合です。値は任意の有効な JSON 型です。標準の JSON 型に加え、Couchbase Lite は 日付 そして ブロブ データ型。必須ではありませんが、推奨される慣行として、 “「type」” 関連するドキュメントの命名空間として機能するプロパティ。.
ユーザープロファイル文書
The sample app deals with a single 文書 with a “「documentType」” 財産の所有者 “「ユーザー」”. ドキュメント ID の形式は “user::<email>”.
文書の例としては、以下のようなものがあります:
{
"surname":"Doe",
"givenName":"Jane",
"jobTitle":"Developer",
"team":"team1",
"email":"demo@example.com"
"documentType":"user",
"imageData":
{
"length":217527,
"content_type":"image/jpeg",
"digest":"sha1-+8y7vkRd2J95kVe/yG2WhuEFa4o=",
"@type":"blob"
},
}
Special ブロブ data type that is associated with the profile image.
Team Membership
The team property designates which team a user is a member of. The team property is a security boundary used as part of the database name, which means users in the same team will use the same database file if a user shares the same physical device or emulator. To simplify things in this learning path, the MockAuthenticationService class defines users and which teams they belong to. Security rules, team membership, and authentication would normally be handled in an OAuth provider or a custom system in an actual mobile application.
ユーザープロファイル
開く UserProfileViewModel.kt ViewModel in the com.couchbase.learningpath.ui.profile directory. For the purpose of this tutorial the “「ユーザー」” 文書 is first stored within an Any of type HashMap<String, Any>.
val profile = HashMap<String, Any>()
profile["givenName"] = givenName.value as Any
profile["surname"] = surname.value as Any
profile["jobTitle"] = jobTitle.value as Any
profile["email"] = emailAddress.value as Any
profile["team"] = team.value as Any
profile["documentType"] = "user" as Any
profilePic.value?.let {
val outputStream = ByteArrayOutputStream()
it.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
profile["imageData"] =
Blob("image/jpeg", outputStream.toByteArray()) as Any
}
について HashMap<String, Any> object functions are used as a data storage mechanism between the app’s UI and the backing functionality of the Couchbase Lite 文書 オブジェクト。.
基本的なデータベース操作
In this section, we will do a code walkthrough of the basic Database operations.
Initialize Couchbase Lite
Before you can start using Couchbase Lite on Android, you would have to initialize it. Couchbase Lite needs to be initialized with the appropriate Android Application Context.
- 開く DatabaseManager.kt ファイルを選択して、
initconstructor.
class InventoryDatabase private constructor (private val context: Context) {
...
init {
//setup couchbase lite
CouchbaseLite.init(context)
...
}
Create and Open a Database
When a user logs in, we create an empty Couchbase Lite database if one does not exist.
- 開く DatabaseManager.kt ファイルを選択して、
initializeDatabases関数です。.
fun initializeDatabases(currentUser: User)
NOTE: You will notice that this code has initialization for two different databases, the inventory database that we will be usign in this step, and the warehouse database. For this step you can ignore the code that initializes the warehouse database as we will cover it in a later step.
- 私たちは、
DatabaseConfiguration内側 DatabaseManager.kt. Each team has their own instance of the Database that is located in a folder corresponding to the team name. Please note that the default path is platform-specific.
val dbConfig = DatabaseConfigurationFactory.create(context.filesDir.toString())
- Then we create a local Couchbase Lite database named “teamname_userprofiles”. If a database already exists, the existing version is returned.
// create or open a database to share between team members to store
// projects, assets, and user profiles
// calculate database name based on current logged in users team name
val teamName = (currentUser.team.filterNot { it.isWhitespace() }).lowercase()
currentInventoryDatabaseName = teamName.plus("_").plus(defaultInventoryDatabaseName)
inventoryDatabase = Database(currentInventoryDatabaseName, dbConfig)
Close a Database
When a user logs out or the app goes to the background, we close the Couchbase Lite database.
- 開く DatabaseManger.kt ファイルを選択して、
closeDatabases()関数です。.
fun closeDatabases() {
- Closing the database is pretty straightforward
inventoryDatabase?.close()
Deleting a Database
Deletion of a database is pretty straightforward and this is how you would do it.
fun deleteDatabases() {
try {
closeDatabases()
Database.delete(currentInventoryDatabaseName, context.filesDir)
Database.delete(warehouseDatabaseName, context.filesDir)
} catch (e: Exception) {
android.util.Log.e(e.message, e.stackTraceToString())
}
}
fun closeDatabases() {
try {
inventoryDatabase?.close()
locationDatabase?.close()
} catch (e: java.lang.Exception) {
android.util.Log.e(e.message, e.stackTraceToString())
}
}
試してみてください
- このアプリはシミュレータまたはエミュレータ、またはデバイスを使用してテストできます。.
- Log in to the app with any username and password. Let’s use the values “demo@example.com“ そして “P@ssw0rd12“ for username and password fields respectively. If this is the first time that the user is signing in, a new Couchbase Lite database will be created. If not, the existing database will be opened.
ドキュメント操作
特定のユーザー用にCouchbase Liteデータベースのインスタンスが作成または開かれたら、基本的な操作を実行できます。 文書 functions on the database. In this section, we will walk through the code that describes basic 文書 オペレーション
ドキュメントの読み取り
Once the user logs in, the user is taken to the “Projects” screen. From this screen the user would tap on the Drawer menu icon (sometimes referred to the Hamburger icon) in the upper left hand corner of the screen and tap on the Update User Profile text button. A request is made to load 「ユーザープロファイル」ドキュメント ユーザーにとって。ユーザーが初めてログインしたときには、何も表示されません。 ユーザープロフィール ユーザー用のドキュメントです。.
- 開く UserProfileRepository.kt ファイルを選択して、
getCurrentUserDocumentIdfunction. This document Id is constructed by prefixing the term “user::” to the email Id of the user.
private fun getCurrentUserDocumentId(currentUser: String): String {
return "user::${currentUser}"
}
- Next, in the UserProfileRepository.kt ファイルを見つけ、
getメソッド。.
override suspend fun get(currentUser: String): Map<String, Any> {
注記:The
getfunction is required by the interface KeyValueRepository found in the file KeyValueRepository.kt.
- We try to fetch the
文書with specifieddocumentIdデータベースから取得したものです。.
val results = HashMap<String, Any>() // <1>
results["email"] = currentUser as Any // <2>
val database = InventoryDatabase.getInstance(context).database
database?.let { db ->
val documentId = getCurrentUserDocumentId(currentUser)
val doc = db.getDocument(documentId) // <3>
if (doc != null) {
if (doc.contains("givenName")) { // <4>
results["givenName"] = doc.getString("givenName") as Any // <4>
}
if (doc.contains("surname")) { // <4>
results["surname"] = doc.getString("surname") as Any // <4>
}
if (doc.contains("jobTitle")) { // <4>
results["jobTitle"] = doc.getString("jobTitle") as Any // <4>
}
if (doc.contains("team")) { // <4>
results["team"] = doc.getString("team") as Any // <4>
}
if (doc.contains("imageData")) { // <4>
results["imageData"] = doc.getBlob("imageData") as Any // <4>
}
}
}
return@withContext results // <5>
- Create an instance of the ユーザープロファイル via
HashMap<String, Any>. - 設定する
メールproperty of the UserProfile with the email Id of the logged-in user. This value is not editable. - Fetch an 不変性 copy of the Document from the Database
- If the document exists and is fetched successfully, we use appropriate type-getters to fetch the various members of the Document based on the property name. Specifically, note the support of the
getBlobtype を入力して、型が type のプロパティの値を取得します。ブロブ - Return the newly constructed ユーザープロファイル オブジェクト。.
ドキュメントの作成/更新
A “User Profile” Document is created for the user when the user taps the “Save” button on the “Edit Profile” view. The method below applies whether you are creating a document or updating an existing version.
- 開く UserProfileRepository.kt ファイルを選択して、
save関数です。.
override suspend fun save(data: Map<String, Any>): Boolean {
- 私たちは創造します 可変性 instance of the Document. By default, all APIs in Couchbase Lite deal with immutable objects, thereby making them スレッドセーフ by design. To mutate an object, you must explicitly get a mutable copy of the object. Use appropriate type-setters to set the various properties of the Document.
val mutableDocument = MutableDocument(documentId, data)
- Save the document.
database?.save(mutableDocument)
}
ドキュメントの削除
We don’t delete a 文書 このサンプルアプリでは、ドキュメントの削除は非常に簡単です。以下はその手順です。.
val document = db.getDocument(documentId)
document?.let {
db.delete(it)
result = true
}
試してみてください
- 「試す」セクションで説明されている手順に従うべきでした。 Create and Open a Database.
- Enter a “First Name”, “Last Name”, and “Job Title” for the user in the Text Entry boxes and Tap “Save”.
- Confirm that you see a “Successfully Updated Profile” toast message. The first time you update the profile screen, the
文書will be created.

- Now tap on the “Photo” image and select an image from the Photo Album. Note that emulators don’t have photos included in most images by default, so you might need to add a photo to select. Also some versions of Android differ in the UI used to browse for images.

- Tap “Save”
- Confirm that you see the toast message “Successfully Updated Profile”. The
文書will be updated this time. - Tap the Drawer menu icon in the upper left hand corner
- Tap “Logout” to log out of the app
- 以前に使用したユーザーのメールアドレスとパスワードでアプリに再度ログインしてください。私の例では、 “demo@example.com“ そして “「P@ssw0rd12」”. (Logging in with those credentials again)
- Tap the Drawer menu icon in the upper left hand corner again
- Confirm that you see the user profile widget with the 名前 そして 画像 以前に設定した値です。.

さらに詳しく
Congratulations on completing the first step of the learning path by reviewing the code that saves User Profiles! In this section, we walked through a very basic example of how to get up and running with Couchbase Lite as a local-only, standalone embedded data store in your Android app. Continue on to the next step to learn how to use a pre-built database with Couchbase Lite.