All CategoriesAndroid App Development

Working with Couchbase Database in Android Apps

Introduction:

Couchbase database is one of the most powerful and complete databases which has a scalability of NoSQL, flexibility of JSON, and the power of SQL. It is a NoSQL document-oriented database which has a storage unit. It is an open source with built-in sync capability. It lives locally on the mobile device and it is a good replacement to Android SQLite.
By using Couchbase, we can build the applications easily and faster with the power of SQL and flexibility of JSON. Couchbase is a combination of CouchDB and Membase, which means it merges from two popular NoSQL technologies.
CouchDB provides the support for storing JSON documents and accessing RESTful API where Membase provides persistence, replication to the high-performance Memcached technology.

Works Offline:

Couchbase database also gives excellent support for offline databases. If our application is based on Couchbase, then we get these features.
Let’s say, we are out and have no signal, but we will still be able to read the Tweets, and even send new Tweets that will be queued to sync once the device comes online.
When we load Tweets, they are loaded from the local Couchbase database without hitting the server.

Real Time Example:

The biggest mobile game, Pokemon Go, also uses Couchbase for its user profiles.

Example with code:

Here, we are going to create a simple example of Couchbase database in our Android application.
Inside this, we see how we can create the database, interact with the database, and perform basic CRUD operations.
This application doesn’t have any UI; we will see the output on the console.
Let’s see how we can do this inside our project.

  • Create a new Application CouchbaseDatabaseExampleAndroid.
  • Now Add the Couchbase Lite maven repository and dependencies in project level and app level build.gradle file.

Add the Couchbase Lite Maven Repository:

Open the project level build.gradle file and add the code here.

repositories {
    mavenCentral()
    maven {
        url "http://files.couchbase.com/maven2/"
    }
}

Here, we add the code in allprojects/repositories section so it can resolve the dependencies through the Couchbase Maven repository.
Add the Couchbase Lite Dependencies:
Open the app level build.gradle file and add the code here.
Here, we add the code in android section.

packagingOptions {
    exclude 'META-INF/ASL2.0'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE'
}

Next, we add the code for Couchbase Lite dependency with the latest version in dependencies section.

dependencies {
        compile 'com.couchbase.lite:couchbase-lite-android:1.3.1'
}

Now, go ahead and do all the operations inside our MainActivity.
MainActivity.java:
This is our main Activity. As we discussed above, here we will create the database and perform basic CRUD operations and do other functionalities in this class.
Add the code in onCreate(..){..}:

final String TAG = "CouchBase Database";
Log.d(TAG, "Begin Couchbase Database");

Create the Manager

Manager manager;
try {
    manager = new Manager(new AndroidContext(this), Manager.DEFAULT_OPTIONS);
    Log.d (TAG, "Manager created");
} catch (IOException e) {
    Log.e(TAG, "Cannot create manager object");
    return;
}

Here, we create the manager because every Couchbase Lite application needs a manager object which manages access to the database. This manager is used later to access the database.
Create Name of the Database

String dbname = "mycouchbasedb";
if (!Manager.isValidDatabaseName(dbname)) {
    Log.e(TAG, "Bad database name");
    return;
}

Database name should be legal and validate because it follows some rules:
The Database name must begin with lowercase letters: a-z
Numbers: 0-9
Special characters: _$()+-/
Create a New Database

Database database;
try {
    database = manager.getDatabase(dbname);
    Log.d (TAG, "Database created");
} catch (CouchbaseLiteException e) {
    Log.e(TAG, "Cannot get database");
    return;
}

Here, we can see very well our database is created.
Create Document Data

SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Calendar calendar = GregorianCalendar.getInstance();
String currentTimeString = dateFormatter.format(calendar.getTime());

Here, we will get the current date and time and then create an object that contains data for a document.

Map<String, Object> docContent = new HashMap<String, Object>();
docContent.put("message", "Hello Couchbase Lite Database");
docContent.put("creationDate", currentTimeString);

HashMap provides JSON compatible representation of data that is suitable for creating documents and for saving into the database. It contains the keys and values. Now, display the data for the new document.

Log.d(TAG, "docContent=" + String.valueOf(docContent));

Create Empty Document and Add Document Data

Document document = database.createDocument();
try {
    document.putProperties(docContent);
    Log.d (TAG, "Document written to database named " + dbname + " with ID = " + document.getId());
} catch (CouchbaseLiteException e) {
    Log.e(TAG, "Cannot write document to database", e);
}
String docID = document.getId();

Here, we create the empty document object by using Document class which is saved to the database. After this, it generates the doc id named _id and revision id named _rev from the stored document.
Retrieve the Document:

Document retrievedDocument = database.getDocument(docID);
Log.d(TAG, "retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));

Here, it retrieves the document from the database by using getDocument() method.
Update the Document:

Map<String, Object> updatedProperties = new HashMap<String, Object>();
updatedProperties.putAll(retrievedDocument.getProperties());
updatedProperties.put ("message", "Whether is not good");
updatedProperties.put ("temperature", "80");
try {
    retrievedDocument.putProperties(updatedProperties);
    Log.d(TAG, "updated retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));
} catch (CouchbaseLiteException e) {
    Log.e (TAG, "Cannot update document", e);
}

To update the document, it is necessary to include the revision id, and after updating the document successfully Couchbase Lite database generates new revision id where document id remains same.
Delete the Document:

try {
    retrievedDocument.delete();
    Log.d (TAG, "Deleted document, deletion status = " + retrievedDocument.isDeleted());
} catch (CouchbaseLiteException e) {
    Log.e (TAG, "Cannot delete document", e);
}
Log.d(TAG, "End CouchBase Dtabase");

Here, it deletes the document by using the delete() method on retrieved documents and shows the status by isDeleted() method.
Output:

Download Source Code: GitHub

Conclusion:

This is a simple example of how to work with Couchbase database in Android applications. Here, we see how the database is created and its basic operations like create, read, update, and delete. It is faster and a much powerful database which is widely used in many applications.
This is a simple example which shows the output on the console. We can create as many powerful applications by using Couchbase database and customizing it according to the need of the application. It is very important and popular in Android development.
Keep visiting www.acadgild.com for more updates on the courses.
Android Programming

Tags

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close