Couchbase Mobile brings the power of NoSQL to the edge. It is comprised of three components:
Couchbase Mobile supports flexible deployment models. You can deploy
This tutorial will walk you through a very basic example of how you can use Couchbase Lite 3.0 in standalone mode within your Android app.
You will learn the fundamentals of
This tutorial assumes familiarity with building Android apps using Java and a computer with the following installed and setup:
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 Document
in the local Couchbase Lite Database
. When the user logs out and logs back in again, the profile information is loaded from the Database
.
User Profile Standalone Demo
repository from GitHub.git clone https://github.com/couchbase-examples/android-java-cblite-userprofile-standalone.git
allprojects {
repositories {
...
maven {
url "https://mobile.maven.couchbase.com/maven2/dev/"
}
}
}
Then add the following to the app/build.gradle file.
dependencies {
...
implementation 'com.couchbase.lite:couchbase-lite-android-ee:3.0.0'
}
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.
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.
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
and Activity
implement.
Couchbase Lite is a JSON Document Store. A Document
is a logical collection of named fields and values. The values are any valid JSON types. In addition to the standard JSON types, Couchbase Lite supports Date
and Blob
data types. While it is not required or enforced, it is a recommended practice to include a "type" property that can serve as a namespace for related documents.
The sample app deals with a single Document
with a "type" property of "user". The document ID is of the form "user::<email>".
An example of a document would be:
{
"type": "user",
"name": "Jane Doe",
"email": "jane.doe@earth.org",
"address": "101 Main Street",
"image": CBLBlob (image/jpg)
}
Special Blob data type that is associated with the profile image.
Open the UserProfilePresenter.java file in the com.couchbase.userprofile.profile directory. For the purpose of this tutorial the "user" Document
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));
}
The 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 Document
object.
In this section, we will do a code walkthrough of the basic Database operations.
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.
initCouchbaseLite
method.public void initCouchbaseLite(Context context) {
CouchbaseLite.init(context);
}
When a user logs in, we create an empty Couchbase Lite database for the user if one does not exist.
openOrCreateDatabaseForUser
method.public void openOrCreateDatabaseForUser(Context context, String username)
DatabaseConfiguration
within DatabaseManager.java. In our case, we would like to override the default path of the database. Every user has their own instance of the Database
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));
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.
registerForDatabaseChanges()
function.private void registerForDatabaseChanges()
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");
}
}
}
}
});
When a user logs out, we close the Couchbase Lite database associated with the user and deregister any database change listeners
closeDatabaseForCurrentUser()
function.public void closeDatabaseForUser()
database.close();
deregisterForDatabaseChanges()
function.private void deregisterForDatabaseChanges()
ListenerToken
associated with the listener.database.removeChangeListener(listenerToken);
Once an instance of the Couchbase Lite database is created/opened for the specific user, we can perform basic Document
functions on the database. In this section, we will walk through the code that describes basic Document
operations
Once the user logs in, the user is taken to the "Your Profile" screen. A request is made to load The "User Profile" Document for the user. When the user logs in the very first time, there would be no user profile document for the user.
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;
}
fetchProfile
method.public void fetchProfile()
Note: The fetchProfile
method is required by UserProfileContract.java, playing a key role in the MVP architecture previously mentioned.
Document
with specified userProfileDocId
from the database.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);
}
Map<String,Object>
.email
property of the UserProfile with the email Id of the logged-in user. This value is not editable.getBlob
type to fetch the value of a property of type Blob
showProfile
method (required by the interface UserProfileContract which is implemented by UserProfileActivity.A The "User Profile" Document 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.
saveProfile
method.public void saveProfile(Map<String,Object> profile)]
MutableDocument mutableDocument = new MutableDocument(docId, profile);
database.save(mutableDocument);
We don't delete a Document
in this sample app. However, deletion of a document is pretty straightforward and this is how you would do it.
var document = database.getDocument(id);
if (document != null) {
database.delete(document);
}
Document
will be created.Document
will be updated this time.Congratulations on completing this tutorial!
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.