Quickstart in Couchbase Lite with Android and Java

  • Learn how to install Couchbase Lite
  • Build an Android App in Java with Couchbase Lite
  • Learn how to Create, Read, Update, and Delete documents

はじめに

Couchbase Mobile brings the power of NoSQL to the edge. It is comprised of three components:

  • Couchbase Lite (カウチベース・ライト), モバイルアプリ用の組み込み型NoSQL JSONドキュメントスタイルデータベースです。.
  • 同期ゲートウェイ, モバイルクライアントとサーバーの間でデータを安全に同期するインターネット対応の同期メカニズムです。.
  • Couchbase Server, 高度に拡張性があり、分散型のNoSQLデータベースプラットフォームです。.

Couchbase Mobile は柔軟なデプロイモデルをサポートしています。デプロイできるのは、

  • Couchbase Liteはモバイルアプリ内のスタンドアロンの組み込みデータベースとして、または,
  • Couchbase Lite enabled mobile clients with a Sync Gateway to synchronize data between your mobile clients or,
  • Couchbase Lite を搭載したクライアントは Sync Gateway を使用して、モバイルクライアントと Couchbase Server の間でデータを同期させることができます。これにより、データをクラウド (パブリックまたはプライベート) に保存できます。

このチュートリアルでは、どのように使用できるかの非常に基本的な例を説明します。 Couchbase Lite 3.0 in standalone mode within your アンドロイド app.

基礎を学ぶ

  • データベース操作
  • Document CRUD Operations via Key/Value Pair

前提条件

This tutorial assumes familiarity with building Android apps using ジャワ and a computer with the following installed and setup:

  • Android Studio Artic Fox (2020.3.1) or above
  • Android SDK installed and setup (v.31)
  • Android Build Tools (> v.31)
  • Android device or emulator running API level 22 or above
  • JDK 8 (now embedded into Android Studio Artic Fox)

アプリの概要

In this tutorial, you will be working with an app 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 データベース.

User Profile App Demo,400

インストール

アプリのソースコードを取得する

ソースコードの複製
  • Clone the User Profile Standalone Demo GitHubからのリポジトリ。.
git clone https://github.com/couchbase-examples/android-java-cblite-userprofile-standalone.git

Installing Couchbase Lite Framework

  • The User Profile Standalone Demo app already contains the appropriate additions for downloading and utilizing the Java 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-ee:3.0.0'
}

試してみてください

  • Android Studioを使用して src/build.gradleを開きます。.
  • プロジェクトのビルドと実行を行います。.
  • ログイン画面が表示されていることを確認してください。.

User Profile Login Screen Image

App Architecture

The sample app follows the MVP pattern, separating the internal data model, from a passive view through a presenter that handles the logic of our application and acts as the conduit between the model and the view.

MVP Architecture

In the Android Studio project, the code is structured by feature. You can select the Android option in the left navigator to view the files by package.

MVP Android Studio

Each package contains 3 different files:

  • Activity: This is where all the view logic resides.

  • Presenter: This is where all the business logic resides to fetch and persist data to a web service or the embedded Couchbase Lite database.

  • Contract: An interface that the Presenter そして Activity implement.

MVP Package

データモデル

Couchbase Lite は JSON ドキュメントストアです。 文書 名前付きフィールドと値の論理的な集合です。値は任意の有効な JSON 型です。標準の JSON 型に加え、Couchbase Lite は 日付 そして ブロブ データ型。必須ではありませんが、推奨される慣行として、 “「type」” 関連するドキュメントの命名空間として機能するプロパティ。.

「ユーザープロファイル」ドキュメント

The sample app deals with a single 文書 with a “「type」” 財産の所有者 “「ユーザー」”. ドキュメント ID の形式は “user::<email>”. 文書の例としては、以下のようなものがあります:

{
    "type": "user",
    "name": "Jane Doe",
    "email": "jane.doe@earth.org",
    "address": "101 Main Street",
    "image": CBLBlob (image/jpg) 
}

Special ブロブ data type that is associated with the profile image.

ユーザープロファイル

開く UserProfilePresenter.java file in the com.couchbase.userprofile.profile directory. For the purpose of this tutorial the “「ユーザー」” 文書 is first stored within an Object of type Map<String, Object>.

Map<String, Object> profile = new HashMap<>();
profile.put("name", nameInput.getText().toString());
profile.put("email", emailInput.getText().toString());
profile.put("address", addressInput.getText().toString());

byte[] imageViewBytes = getImageViewBytes();

if (imageViewBytes != null) {
  profile.put("imageData", new com.couchbase.lite.Blob("image/jpeg", imageViewBytes));
}

について Map<String, Object> 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. Starting with v2.6, Couchbase Lite needs to be initialized with the appropriate Android Application Context.

public void initCouchbaseLite(Context context) {
  CouchbaseLite.init(context);
}

Create and Open a Database

ユーザーがログインすると、ユーザーがまだ存在しない場合は、空のCouchbase Liteデータベースを作成します。.

  • 開く DatabaseManager.java ファイルを選択して、 openOrCreateDatabaseForUser メソッド。.
public void openOrCreateDatabaseForUser(Context context, String username)
  • 私たちは、 DatabaseConfiguration 内側 DatabaseManager.java. In our case, we would like to override the default path of the database. Every user has their own instance of the データベース that is located in a folder corresponding to the user. Please note that the default path is platform-specific.
DatabaseConfiguration config = new DatabaseConfiguration();
config.setDirectory(String.format("%s/%s", context.getFilesDir(), username));
  • Then we create a local Couchbase Lite database named “userprofiles” for the user. If a database already exists for the user, the existing version is returned.
database = new Database(dbName, config);

データベースの変更の聞き取り

You can be asynchronously notified of any change (add, delete, update) to the Database by registering a change listener with the Database. In our app, we are not doing anything special with the Database change notification other than logging the change. In a real-world app, you would use this notification, for instance, to update the UI.

  • 開く DatabaseManager.java ファイルを選択して、 registerForDatabaseChanges() 関数です。.
private void registerForDatabaseChanges()
  • We register a change listener with the database. This is an optional step. We track the ListenerToken as it is needed for removing the listener.
// Add database change listener
listenerToken = database.addChangeListener(new DatabaseChangeListener() {
  @Override
    public void changed(final DatabaseChange change) {
      if (change != null) {
        for(String docId : change.getDocumentIDs()) {
          Document doc = database.getDocument(docId);
            if (doc != null) {
              Log.i("DatabaseChangeEvent", "Document was added/updated");
            }
            else {
             Log.i("DatabaseChangeEvent","Document was deleted");
            }
        }
      }
    }
});

Close a Database

When a user logs out, we close the Couchbase Lite database associated with the user and deregister any database change listeners

  • 開く DatabaseManager.java ファイルを選択して、 closeDatabaseForCurrentUser() 関数です。.
public void closeDatabaseForUser()
  • Closing the database is pretty straightforward
database.close();

De-registering from Database Changes

  • 開く DatabaseManager.java ファイルを選択して、 deregisterForDatabaseChanges() 関数です。.
private void deregisterForDatabaseChanges()
  • We stop listening to database changes by passing in the ListenerToken associated with the listener.
database.removeChangeListener(listenerToken);

試してみてください

  • このアプリはシミュレータまたはエミュレータ、またはデバイスを使用してテストできます。.
  • Log in to the app with any username and password. Let’s use the values “demo@example.com“ そして “password“ それぞれ「ユーザー名」と「パスワード」フィールドです。ユーザーが初めてログインする場合、新しいCouchbase Liteデータベースが作成されます。そうでなければ、ユーザーの既存のデータベースが開かれます。.

ドキュメント操作

特定のユーザー用にCouchbase Liteデータベースのインスタンスが作成または開かれたら、基本的な操作を実行できます。 文書 functions on the database. In this section, we will walk through the code that describes basic 文書 オペレーション

ドキュメントの読み取り

ユーザーがログインすると、「あなたのプロフィール」画面が表示されます。ロードを要求するリクエストが送信されます。 「ユーザープロファイル」ドキュメント ユーザーにとって。ユーザーが初めてログインしたときには、何も表示されません。 ユーザープロフィール ユーザー用のドキュメントです。.

  • 開く DatabaseManager.java ファイルを選択して、 getCurrentUserDocId method. This document Id is constructed by prefixing the term “user::” to the email Id of the user.
public String getCurrentUserDocId() {
  return "user::" + currentUser;
}
public void fetchProfile()

注記:The fetchProfile method is required by UserProfileContract.java, playing a key role in the MVP architecture previously mentioned.

  • We try to fetch the 文書 with specified userProfileDocId データベースから取得したものです。.
String docId = DatabaseManager.getSharedInstance().getCurrentUserDocId();

if (database != null) {
  Map<String, Object> profile = new HashMap<>();

  profile.put("email", DatabaseManager.getSharedInstance().currentUser);

  Document document = database.getDocument(docId);

  if (document != null) {
    profile.put("name", document.getString("name"));
    profile.put("address", document.getString("address"));
    profile.put("imageData", document.getBlob("imageData"));
  }
  mUserProfileView.showProfile(profile);
}
  • Create an instance of the ユーザープロファイル via Map<String,Object>.
  • 設定する メール 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 getBlob type を入力して、型が type のプロパティの値を取得します。 ブロブ
  • Using the newly constructed ユーザープロファイル update the UI via the showProfile method (required by the interface UserProfileContract which is implemented by UserProfileActivity.

ドキュメントの作成/更新

A 「ユーザープロファイル」ドキュメント is created for the user when the user taps the “Save” button on the “Profile Screen”. The method below applies whether you are creating a document or updating an existing version.

public void saveProfile(Map<String,Object> profile)]
  • 私たちは創造します 可変性 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.
MutableDocument mutableDocument = new MutableDocument(docId, profile);
  • Save the document.
database.save(mutableDocument);

ドキュメントの削除

We don’t delete a 文書 このサンプルアプリでは、ドキュメントの削除は非常に簡単です。以下はその手順です。.

var document = database.getDocument(id);

if (document != null) {
    database.delete(document);
}

試してみてください

  • 「試す」セクションで説明されている手順に従うべきでした。 Create and Open a Database.
  • Enter a “name” for the user in the Text Entry box 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.

User Profile Document Creation

  • Now tap on the “Upload Photo” button and select an image from the Photo Album.

image selection

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

log off

さらに詳しく

このチュートリアルを完了していただきありがとうございます!

This tutorial walked you 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. If you want to learn more about Couchbase Mobile, check out the following links.

関連書籍

データベースの膨大なサイズを過去のものとしておく

スタックの追加ごとに新たな請求書が発生し、管理するものがさらに増えます。2分でどれだけの節約ができるかを試算してください。.