This multipart blog will help you build an end-to-end mobile application using Couchbase Lite. State of the art end-to-end, scalable and production-grade applications include the following features:
-
- Um banco de dados incorporado – storing data locally reduces network trips to a centralized database for every activity. This is crucial for improving the user experience.
- Synchronization with other peer mobile devices and with a centralized server.
- Advanced analytics capabilities, full-text search and machine learning on the device.
Since there’s a lot to cover, we’ve split this project into three parts. Part 1 showcases the process for building a mobile application that leverages Couchbase Lite and uses it as an embedded database to store data. Part 2 will show how to run Full Text Search (FTS) on the device. And part 3 will showcase the process of syncing the data with peers and a centralized Couchbase server.
O que é o Couchbase Mobile?
Couchbase Mobile includes:
-
- Embedded Couchbase Lite database for edge devices
- High-performance Gateway de sincronização for peer to peer and centralized server synchronization
- Edge data centers powered by Servidor Couchbase that can be deployed on the cloud, on-prem or in local edge data centers.
Mobile application overview
The code for this demo application is in my Couchbase Mobile GitHub repository. Baixar Rateit.zip and extract the files to your local folder. Alternatively, you can follow the instructions in this blog to build the app from scratch.
A funcionalidade do aplicativo é dividida em três partes:
-
- Enviar solicitações de classificação
- Receive rating requests from others
- Viewing the rated request returned from others
Send Rating Requests
The app that we will build in this application sends a rating request to a person and receives the rated request back.
O ENVIAR PARA field indicates the phone number of the person to whom you want to send the request. The MENSAGEM field indicates what you want them to do with it. In this case, since it is a rating request, I have a predefined message of “Rate 1-5”, indicating they need to supply a rating when they send the request back.
O SUBJECT field indicates any topic on which you want a rating, for example, like one of these:
Ator: Chris Hemsworth
Livro: Orgulho e Preconceito
www.google.com
There are no strict edit validations on the fields, but that is something you would do when you build a production-grade mobile app.
Quando você clica em ENVIAR, a request is sent to the person you want a response from. Since we will be talking about syncing peer-to-peer with other devices, and with a centralized server in a future post, here we focus on the local offline mode functionality.
Received Rating Requests
This section in the app lets you respond to rating requests received from others. We define a rating bar that lets you put in the number of stars for your rating.
Just so I remain within the scope of this app when I send a request, I hardcoded values for remetente e receptor. I have used Sandhya as the sender and Rangana as the receiver. This section will display all the requests for Rangana, i.e., where the PARA field is equal to Rangana.
Incoming Rated Requests
This section lists all the requests that you sent and received a rating back for.
Now let’s walk through an example to make all the sections clear.
First, we send a request to phone number 732-600-7000 with a message to rate the book Pride and Prejudice.
When you click on SOLICITAÇÕES DE CLASSIFICAÇÃO RECEBIDAS it is actually showing me the ones that I sent to someone else, just for demo purposes here. In the real world, it would go to the actual person to whom this is addressed.
I select a four-star rating and click on the RATE button, which initiates returning it to the send (this rated request goes back to me as shown below):
Now when clicking on SOLICITAÇÕES CLASSIFICADAS RECEBIDAS, we can see if the rating made it back to me, the sender. You can see that it came back and listed my rating of 4.0 stars.
O DELETE button is available for you to remove that particular row now.
Now, let’s build the app!
Getting Started: Review CBLite Documentation
Please review the documentação to understand the various components of a Couchbase Lite database application. For this app, I create a brand new database when the application is invoked for the first time. Alternatively, the app can also use a pre-built database.
The steps to embed the database can be found here in the Documentação do Couchbase Lite. Review each of the sections to learn the following concepts:
-
- creating and opening a database
- writing a document into the embedded database
- writing queries to retrieve the document
- expiring or deleting a document
App building prerequisites
This app has been built for Android devices using the following software and hardware prerequisites that you need to be aware of:
-
- You need to understand the basics of building apps with Android Studio and programming in Java.
- This demo app and related screenshots come from building the app on a MacOS computer.
- We use the, freely available, Android Studio 2020.3 to build mobile apps for Android devices.
- Couchbase Lite version 3.0.0-beta02 is used. The required libraries will be embedded in the code and there is no need to download the software manually to your desktop.
Building the application
Ensure that Android Studio is installed on your desktop and create a new project, choosing Empty Activity as the project type. Android Studio builds a template of the main page for you based on what you pick. I chose this one because I want to build a customized app front page.
You can see the different settings I used in the New Project form. This creates an app that will display “hello world” when compiled and run on an emulator. In order to create an emulator for the app click on Tools → AVD Manager → Create virtual Device.
This gives you a list of devices you can emulate without having to acquire the actual device and compile or deploy the code on it. I used NEXUS 5X API 25.
When you run the emulator the following screen shows the basic, empty, application:
From here we build the actual Rateit app components:
Localize o build.gradle(Module.App.rateit) and modify the contents to match the following:
-
- O compileSDK e minSDK version for the emulator you choose.
- The Java version you have.
- Add the following implementation line in the dependencies section:
1 |
implementation 'com.couchbase.lite:couchbase-lite-android:3.0.0-beta02' |
Layouts
Layout files are XML files that describe the mobile application screen. O activity_mail.xml file will be present in the project folder and needs to be replaced by the XML file from the GitHub code. The rest of the XML files can be added by right-clicking on layout → New → XML → Layout XML File.
There are three more layout XML files to create:
activity_main.xml
This has the ENVIAR PARA, MENSAGEM, SUBJECT campos in addition to the two list views for the Sent e Recebido requests. It also defines which function to invoke when the CLIQUE PARA ENVIAR SOLICITAÇÃO DE CLASSIFICAÇÃO, SOLICITAÇÕES DE CLASSIFICAÇÃO RECEBIDAS e SOLICITAÇÕES DE CLASSIFICAÇÃO RECEBIDAS buttons are pressed. The XML code can be written or it can be generated by setting the attributes in the atributos section of the designer.
CustomLayout.xml
This has the Listview and the layout for all the SOLICITAÇÕES DE CLASSIFICAÇÃO RECEBIDAS and defines which function to invoke when the Rate e Excluir buttons are pressed.
CustomLayoutRated.xml
This layout has the Listview and the layout for all the SOLICITAÇÕES CLASSIFICADAS RECEBIDAS and also defines which function to invoke when the Excluir button is pressed.
The Rateit App
The main page of the app has three buttons:
-
- CLIQUE PARA ENVIAR SOLICITAÇÃO DE CLASSIFICAÇÃO
- SOLICITAÇÕES DE CLASSIFICAÇÃO RECEBIDAS
- SOLICITAÇÕES DE CLASSIFICAÇÃO RECEBIDAS
O mainactivity.java file will be present in the project folder and needs to be replaced by the code from the GitHub repository. The rest of the Java files can be added by clicking on Java, highlighting com.example.rateit and right-clicking on New → Java Class. Create classes for each of:
-
- User.java
- UserCustomAdapter.java
- Rated.java
- RatedCustomAdapter.java
Reviewing the code
Mainactivity.java
Localizar Mainactivity.java sob o Java → com.example.rateit folder and paste the following code inside the class MainAcivity.
O senddata function gets activated when CLIQUE PARA ENVIAR SOLICITAÇÃO DE CLASSIFICAÇÃO is clicked. It collects all the input fields and creates two documents—one of Type Send and one of type Recebido. The received record type helps us see records in the SOLICITAÇÕES DE CLASSIFICAÇÃO RECEBIDAS.
Note that Part 2 of the blog series will show the peer-to-peer sync feature and the writing of the received record will be removed because the second device will be receiving this request.
O receivedata function gets activated when SOLICITAÇÕES DE CLASSIFICAÇÃO RECEBIDAS is clicked and it displays all the rating requests received. It executes a query against the local database to get the records. It lets you put in a rating and creates a JSON record with the rating when the RATE button is clicked, writing the request back to the database with a document type of rated. If the DELETE button is clicked, the record is deleted but setting the TTL (Time to Live) of the document to expire.
O incomingratings function gets activated when the SOLICITAÇÕES DE CLASSIFICAÇÃO RECEBIDAS button is clicked and it displays all the ratings sent by the user that were rated by others and came back. When the DELETE button is pressed the TTL (Time to Live) attribute is set to expire.
Rated.Java holds the Classificado class and sets and gets the various attributes of the records
RatedCustomAdapter.java e RatedHolder.java will populate the listview. The layout is defined in CustomLayoutRated.xml
User.java has the get and set functions for document attributes required to populate the RECEIVED RATING REQUEST listview.
UserCustomAdapter.java e UserHolder.java has the RECEIVED RATING REQUEST listview including the Rating Bar, the contents of the record and the RATE e DELETE botão
Once all these pieces of code are placed in the appropriate folders and files in the app, the project folder will look like this:
Compiling the code
Quando todo o código tiver sido atualizado, clique em Build → ReBuild Project. Once it succeeds click on Criar → Executar.
You will be asked to choose the emulator the first time you run the app, e.g., choose the NEXUS 5X API 25 like I did. Once the run is complete the main page will look like this:
Agora você implantou com êxito o código no emulador de sua escolha.
Próximas etapas
This is the first part of the blog series, Building a Mobile Application with Couchbase, which focuses on a complete end-to-end mobile solution. This post showed how to build an offline mobile app with a local, embedded, Couchbase Lite database.
In the next part of the series, we will build with the Sync Gateway feature to showcase the peer-to-peer sync feature as well as syncing with a centralized Couchbase Server cluster.
The main resources referenced in this post included: