React Native enables you to build Android applications that look and feel native with only JavaScript. In this instance, React Native takes care of managing UI state and synchronizing it with the models. And luckily for us, we can use Couchbase Lite to add sync and persistence to a React Native app. In this tutorial, you will learn how to build a simple application to save documents and replicate them to Pasarela de sincronización. Here are the core concepts you will learn:

  1. Create a basic project with Couchbase Lite Android and Couchbase Lite Java Listener
  2. Integrating React Native in your project
  3. Adding Models and UI components with JavaScript
  4. Setting up Couchbase Sync Gateway

Here’s a sneak peek of what you are going to build:

todolite

You can download the completed project from GitHub.

Requisitos previos

Primeros pasos

In this section, you will create a new Android Studio project from scratch and integrate React Native to it.

New Android Studio Project

Before you start writing some JavaScript you need to create a new Android Studio project with all the dependencies. Open Android Studio and from the welcome screen select Nuevo proyecto. In the New Project window, enter TodoLite ReactNative Android for the application name and todolite-reactnative-android for the folder name:

newprojectandroidstudio

Set the minimum required SDK to API 16: Android 4.1 or later and use the currently recommended Android API. After you fill in the fields, the New Project window should look something like this:

api_16_android_jelly_bean

Click Next, and choose the Actividad en blanco plantilla:

 blank_activity blank_activity

Haga clic en Acabado and you should see the following in the project navigator:

finish

Bundling dependencies

Expand the app folder, and then open the build.gradle file. Make sure you open the one located in the aplicación folder (also called the module) and add the following in the android sección:

Next, open build.gradle at the root (also referred to as the project level gradle file) and add a reference to the Couchbase Maven repository:

Now, add the following lines to the top-level dependencias sección:

In the Android Studio tool bar, click Sync Project with Gradle Files.

Setting up Couchbase Lite and the Listener

Abrir AndroidManifest.xml located in app/src/main and add the permissions:

The React Native Android Activity

You need to add some native code in order to start the React Native runtime and get it to render something. Replace the content of MainActivity.java with the following and we’ll explain what is going on next:

A few things are happening here:

  1. You create an Activity that creates a ReactRootView, starts a React application inside it and sets it as the main content view. Next, you’re calling the initCBLite method which does a few things.
  2. Here you define an empty name and password to be used by the Listener. This means that in theory, anyone could access your database. This is ok for this tutorial but in production you’d replace the line with new Credentials().
  3. Plug in the component to compile the JavaScript Views. We’re not going to use Couchbase Views in this tutorial just yet but it might come in handy.
  4. Instantiate the Director and enable logging.
  5. Start the Couchbase Listener passing in the port to listen on, the manager instance and secure credentials.

That’s all for the Android part, now you can turn your attention to JavaScript!

JavaScript Land

In your project’s root folder, run:

This creates a node module for your app and adds the react-native npm dependency. Now open the newly created paquete.json file and add this line inside of the guiones campo:

Hola Mundo

Copy & paste the following code to a new index.android.js file in your root folder:

Build and Run!

To run your app, you first need to start the development server. To do this, simply run the following command in your root folder:

NOTA: At the time of this writing, you may need to run brew update && brew reinstall watchman to update watchman if you get the error Error building DepdendencyGraph: TypeError: Cannot read property 'root' of null.

Now build and run your Android app in a new Terminal tab:

Open it in the Android simulator and you will see the following:

helloworld

Well done on getting the development environment up and running! React Native includes great features such live reload which make it much easier to iterate on the UI of the application, but first you must define the models and methods to persist documents to the Couchbase Lite database.

A Todo Application

A Simple API

Crear un nuevo archivo app/utils/api.js y añade lo siguiente:

Here is what you’re doing:

  1. You declare the endpoint the Couchbase Listener is running on.
  2. The remote database is Sync Gateway in this case. This would be replaced with your Sync Gateway production instance.
  3. The method to persist a task document.
  4. Here, you’re getting all the documents from Couchbase Lite.
  5. Start a push replication from the Couchbase Lite database to Sync Gateway. There could equally be a pull replication as well.

With a basic API in place, you can now turn your attention to building the UI.

Building the UI

Create a new file in app/components/Home.js with the following:

Don’t get intimidated by the length of this code snippet. All we’re doing here is declaring styles and using some built-in React Native UI components to display a text input, buttons and text labels. You can find the list of built-in UI components aquí.

Updating the Root Component

The final step before you can see your great work in action is to update index.android.js to load the Inicio component. Below the requiere statement to import react-native, add the following:

Next, replace the return value of the render method with . Use the ⌘ + m shortcut in Genymotion to reload the JavaScript and you should see a bright blue screen. That’s good news!

 savesync

Replications with Couchbase Sync Gateway

Descargue Sync Gateway desde el siguiente enlace y descomprima el archivo:

http://www.couchbase.com/nosql-databases/downloads

En un nuevo archivo llamado sync-gateway-config.json, paste the following:

And run Sync Gateway with this config file:

To make the Sync Gateway endpoint reachable inside of the Android VM emulator, you need to enable a port from the host to the VM. In Terminal, run the following:

Open the Admin UI to monitor the documents that were saved to Sync Gateway:

http://localhost:4985/_admin/

Try adding more task documents and notice how they get pushed to Sync Gateway automatically.

Where To Go From Here

Congratulations! You’ve built your first React Native Android + Couchbase Lite application. You’re now ready to add more components such as the following:

  1. Couchbase Lite Views to write custom queries
  2. User authentication in a replication
  3. Continuously deploying the Sync Gateway configuration file and other components

Watch out for a tutorial on debugging your React Native Android + Couchbase Lite application using Charles and Genymotion.

No dudes en compartir tus opiniones, hallazgos o preguntas en los comentarios o en los foros. ¡Hasta pronto!

Autor

Publicado por James Nocentini, Redactor técnico, Móvil, Couchbase

James Nocentini es el escritor técnico encargado de la documentación de Couchbase Mobile. Anteriormente, trabajó como Developer Advocate y antes de eso como desarrollador front-end para HouseTrip. También disfruta escribiendo tutoriales de Android para raywenderlich.com en su tiempo libre.

1 Comentarios

  1. *Open AndroidManifest.xml located in app/src/main and add the permissions:*
    the above line states the permissions but none found in the box given below of it. please add those lines.

Dejar una respuesta