The Basics
Initialization
To get started, you must initialize Couchbase Lite with the relevant application context
Open the file DatabaseManager.java.
DatabaseManager.java
public DbManager(@Nonnull DbExecutor exec) {
this.exec = exec;
CouchbaseLite.init();
final ConsoleLogger logger = Database.log.getConsole();
logger.setLevel(LogLevel.DEBUG);
logger.setDomains(LogDomain.ALL_DOMAINS);
}
Create a Database
There is no limit to how many databases can be created or opened on the device. You can think of a database as a namespace for documents and several databases can be used in the same app (one database per user of the app is a common pattern).
The snippet below creates an empty database for the guest user in a directory named guest.
Open the file DatabaseManager.java.
We will review the openGuestDb() method.
public void openGuestDb() {
...
}
We create a folder for the guest user database if one does not exist and specify that as the database directory in the DatabaseConfiguration object.
final DatabaseConfiguration config = new DatabaseConfiguration();
config.setDirectory(new File(DB_DIR, GUEST_USER).getCanonicalPath());
The Couchbase Lite Database is created with specified name and DatabaseConfiguration object.
database = new Database(DB_NAME, config);
Create and Update a Document
Bookmarked hotels are persisted in a separate document with a type of bookmarkedhotels.
The first time a hotel is bookmarked, the bookmarkedhotels document is created with the document ID of that hotel document in the hotels property.
The hotel’s information is persisted in a separate hotels type document.
Subsequently, every time a hotel is bookmarked, the process repeats.
{
"_id": "hotel1",
"name": "San Francisco Hotel",
"address": "123, Park Street, San Francisco"
}
{
"type": "bookmarkedhotels",
"hotels": ["hotel1", "hotel2"]
}
Open the file BookmarkDao.java.
You will review the addBookmarksAsync method.
@Nullable
private Void addBookmarksAsync(@Nonnull Set<Hotel> hotels) throws CouchbaseLiteException {
...
}
First, you need to get an instance of the database.
final Database database = db.getDatabase();
The following snippet persists the hotel instance (Set<Hotel>) as a new Document in the database.
This will allow us to access bookmarked hotel documents while being offline.
final Set<String> ids = new HashSet<>();
for (Hotel hotel : hotels) {
final String id = hotel.getId();
final Document hotelDoc = database.getDocument(id);
if (hotelDoc == null) { database.save(Hotel.toDocument(hotel)); }
ids.add(id);
}
bookmarkIds(database, ids);
Next you will get the document with ID user::guest or create one if it doesn’t exist.
This is implemented in the bookmarkIds private method.
private void bookmarkIds(@Nonnull Set<String> ids) throws CouchbaseLiteException {
...
}
The document is created with the type property set to bookmarkedhotels and a new hotels array to store the document IDs of the bookmarked hotels.
final MutableDocument guestDoc = db.getGuestDoc();
final Set<String> currentBookmarks = new HashSet<>();
final MutableArray bookmarks = guestDoc.getArray(PROP_BOOKMARKS);
if (bookmarks != null) {
for (int i = 0; i < bookmarks.count(); i++) { currentBookmarks.add(bookmarks.getString(i)); }
}
currentBookmarks.addAll(ids);
Next, the selected hotel’s ID is added to the hotels array.
final MutableArray newBookmarks = new MutableArray();
for (String bookmark : currentBookmarks) { newBookmarks.addString(bookmark); }
guestDoc.setArray(PROP_BOOKMARKS, newBookmarks);
Finally, you will save the document.
db.getDatabase().save(guestDoc);
Delete a Document
A document can be deleted using the delete method.
This operation actually creates a new tombstoned revision in order to propagate the deletion to other clients.
Open the file BookmarkDao.java.
You will review the removeBookmarksAsync method.
@Override
Void removeBookmarksAsync(@Nonnull Set<Hotel> hotels) throws CouchbaseLiteException {
...
}
When a hotel is bookmarked, it gets inserted in the Couchbase Lite database for offline access. So when the user unbookmarks a hotel, the document needs to be removed from the database. That’s what the code below is doing.
final Database database = db.getDatabase();
final Set<String> ids = new HashSet<>();
for (Hotel hotel : hotels) { ids.add(hotel.getId()); }
unbookmarkIds(ids);
for (String id : ids) {
final Document hotelDoc = database.getDocument(id);
if (hotelDoc == null) {
LOGGER.log(Level.WARNING, "Hotel not found in remove bookmark: " + id);
continue;
}
database.delete(hotelDoc);
}
In addition to deleting the document of type "hotel" as shown above, the unbookmarking process removes the hotel ID from the hotels array in the "bookmarkedhotels" document.