The RecyclerView widget is a popular option on the Android platform for efficiently displaying dynamic data collections. The data items feeding the RecyclerView may change as a result of user’s actions or with data fetched from the network. As the name indicates, RecyclerViews recycle the views that correspond to the items in the data sets. In this post, we discuss how you can use Couchbase Lite as a data source for RecyclerViews in your Android application.
We will use Couchbase Mobile 2.0 although everything that is discussed here will apply to 1.x versions of Couchbase Mobile as well.

Background

The Couchbase Mobile Platform comprises of the Couchbase Lite NoSQL embedded database running on clients, the Sync Gateway responsible for data synchronization, data routing and user authentication/authorization and Couchbase Server for data persistence and management. We will only be dealing with Couchbase Lite in our discussions here.

The post assumes that you are familiar with fundamentals of how to integrate Couchbase Lite into your Android app. If you need a refresher or are unfamiliar with getting started with Couchbase Lite on Android, refer to our tutorial site.
We also assume that you are familiar with the basics of developing apps on Android and with RecyclerViews.

Sample App

The sample app that is discussed here is available for dowload from Github.

The app is very simple. It does one thing. It displays a list of items in a Recyclerview and Couchbase Lite is used as the data source.

Build and run the app in Android Studio.
Tap on the “ADD UNIVERSITY” button. This will result in a new document getting added to the RecyclerView. Now let’s see how this works.

Design

A typical design pattern for using Couchbase Lite as the data source for the RecyclerView in your app is shown below. This also corresponds to the way we have implemented it in the sample app.

Here are the key elements –
– The RecyclerView is instantiated by the Activity and contains the Adapter .
– The Adapter is responsible for binding the data items to the view using the ViewHolder pattern.
Couchbase Lite is the data source for the data items that is used for populating the views.
– The Database Manager which is a singleton class is used for initialization and management of Couchbase Lite.
– The Couchbase Lite Live Query API for interacting with the database. A Couchbase Lite Live Query allows an app to register for changes to the database that affect the results of the query using the addChangeListener call.

This is the sequence –
The Activity uses the Couchbase Lite Live Query to query for data items in the database and a listener is registered to handle query data updates. Every time the database gets updated with data that affects the query results, the Activity is notified of the changes via the listener callback. After retrieving the data from the Couchbase Lite database, the Adapter is notified of the changes. The RecyclerView is then updated with the updated data set.

How the data gets into Couchbase Lite is not important to this discussion. In a real world app, the data in Couchbase Lite may be fetched from a remote server or may be updated as a result of the local user’s action.

App Walkthrough

Initialization

Open the ListActivity.java file and locate the onCreate() method.
This is where all the initialization takes place. In addition to the typical content layout initialization, the DatabaseManager and the DataFetcher objects are instantiated. The RecyclerView is instantiated with the UniversityListAdapter adapter and the appropriate Layout Manager.


Loading Sample Data

Open the DataFetcher.java file. During Activity Launch, the DataFetcher class loads the sample data. The loading of data is done on a background thread using AsyncTask.

  1. The sample data is loaded from the university-sample.txt file in the assets folder. The content is in JSON format.
  2. Once the data is read, The JSON data is mapped to corresponding University POJO objects using the Jackson library.
  3. ListActivity is notified of the completion of data load via the IDataFetchResponse interface.

Note: The sample data is not saved into the database at this point. It is in an in-memory data structure called sampleData in the ListActivity class. We will see how this sample data is used a little later in the post.

Updating Adapter Data Sets with Couchbase Lite Data

When the Activity is notified that the sample data set has been loaded via the IDataFetchResponse interface, it creates a Live Query to fetch documents from the database.
Open the ListActivity.java file and go to the QueryForListOfUniversities() method.

  1. A LiveQuery is created that fetches all documents from Couchbase Lite database
  2. A listener is registered to listen to all database changes that impact the query
  3. In the listener callback
    • Iterate over changed rows, fetch the documents corresponding to and convert it to University POJOs.
    • Update the adapter with the changed documents
  4. Notify the adapter of the updated data set that will cause the RecyclerView to be reloaded with the updated data
  5. Run the Query

Triggering Database Updates

Open the ListActivity.java file and go to the fetchUniversityAndAddToDatabase() method. In the section on Sample Data, we described how sample data was loaded into an in-memory sampleData List data. The fetchUniversityAndAddToDatabase method is invoked every time the user taps on the “ADD UNIVERSITY” button and is used to insert a data item from the sample data into Couchbase Lite. (As mentioned above, in a real world app, the data in Couchbase Lite may be fetched from a remote server or may be updated as a result of the local user’s action)

  1. A random row from the sampleData List of University objects is selected
  2. The Universty object is converted to Couchbase Lite Document using Jackson library
  3. The Document is inserted into the database. This insertion triggers the LiveQuery listener to be invoked.

Resources

That’s it! That’s all that’s needed to get Couchbase Lite’s Live Queries to work with RecyclerViews. We have used Couchbase Lite V2.0 in our example but everything that’s discussed here applies to V1.x as well. Refer to the developer portal to learn more about Couchbase Mobile APIs.

If you have questions or feedback, please leave a comment below or feel free to reach out to me at Twitter @rajagp or email me priya.rajagopal@couchbase.com. The Couchbase Forums are another good place to reach out with questions.

 

Posted by Priya Rajagopal, Developer Advocate, Couchbase

Priya Rajagopal is a Mobile Developer Advocate for Couchbase, living in Ann Arbor, MI. She has been professionally developing software for over 18 years and was most recently the Director of Mobile Development at a startup. Although her current interests lie in mobile development, she has previously worked on a range of technologies including IPTV, Social TV, targeted advertising, network management , RESTful architectures and platform security. As a TISPAN IPTV standards delegate, she was a key contributor to the IPTV architectural specifications.
She has spent a decade in software R&D and is a co-inventor on almost 2 dozen US patents.

Leave a reply