Saving Data with an ObjectBox Database on Android

In this tutorial, you’ll learn about saving data with an ObjectBox database on Android. You’ll also learn about the different types of databases. By Subhrajyoti Sen.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

Deleting an Entity

Deleting an entity in ObjectBox is pretty straightforward. You need the entity id. The syntax for removing an entity is the following. Don’t worry about adding it until the next step:

objectBox.remove(entityId)

Open BorrowedItemActivity and add the following code inside deleteBorrowedItem():

if (borrowItemToBeEdited != null) {
      // force unwrap (not-null assertion) here is fine since id can't become
      // null once set.
      borrowBox.remove(borrowItemToBeEdited!!)
      Toast.makeText(this,  "Removed note with title " +
              borrowItemToBeEdited?.itemName, Toast.LENGTH_LONG).show()
      finish()
    }

First, this checks if you’re editing an existing entity. Then it removes the entity from the Box using the entity’s id.

Build and run the project. Click any row in the list and then click the Delete icon on the toolbar. You’ll notice that the row corresponding to your entity is removed.

the row corresponding to your entity is edited

Sorting the Entities

You might want to sort the list of entities by the date added or the name of the borrowed item. Remember the toolbar menu items that didn’t do anything? You’ll make them functional in this section.

But first, take a look at how you’d sort the entities from the database.

You need to use order() while building the query. To make the query return items sorted by the name of the borrowed item, you need a query like this:

borrowBox.query()
  .order(BorrowedItemModel_.itemName)
  .build()

Remember that BorrowedItemModel_ is the class generated by ObjectBox for your entity.

Open MainActivity.kt. By default, your original query sorts the entities by the order in which they were added. So right-click on the declaration for borrowQuery and from the context menu choose Refactor ‣ Rename and rename it to borrowDateSortQuery.
rename it borrowDateSortQuery

Next, add a field to store a query to sort by name just below:

private lateinit var borrowNameSortQuery: Query<BorrowedItemModel>

Then in onCreate(), add the query to sort the items based on name as shown below:

borrowDateSortQuery = borrowBox.query()
      .order(BorrowedItemModel_.borrowDate)
      .build()

After that, add the following to sort by name:

borrowNameSortQuery = borrowBox.query()
      .order(BorrowedItemModel_.itemName)
      .build()

Now all you need to do is switch your query based on the selected option in the menu. To do this, modify the block inside onOptionsItemSelected() as below:

   // Handle item selection
    when (item.itemId) {
      R.id.sort_by_name -> {
        subscription.cancel()
        subscription = borrowNameSortQuery.subscribe()
          .on(AndroidScheduler.mainThread())
          .observer { notes -> 
            borrowRecyclerViewAdapter.setBorrowedItemList(notes) 
          }
      }
      R.id.sort_by_date_added -> {
        subscription.cancel()
        subscription = borrowDateSortQuery.subscribe()
          .on(AndroidScheduler.mainThread())
          .observer { notes -> 
            borrowRecyclerViewAdapter.setBorrowedItemList(notes) 
          }
      }
    }
    item.isChecked = true
    return super.onOptionsItemSelected(item)

Whenever you select a new menu item, the previous subscription cancels. It also starts a new subscription based on the menu selection.

Build and run the project. Click the Sort icon and select the Name option. You’ll notice the list of items is sorted by item name and that it also updates. Make sure to have multiple list items so you can see the difference.

the list of items is sorted by item name

Searching for Entities

If many people borrow items from you, it might become difficult for you to look them up. Time to add search functionality! With it, the user can search based on the name of the borrowed item.

Replace queryForText() with the following:

  private fun queryForText(query: String) {
    val items = borrowBox.query()
      .contains(BorrowedItemModel_.itemName, query)
      .build()
      .find()

    borrowRecyclerViewAdapter.setBorrowedItemList(items)
  }

contains() checks if a certain field in the database contains a given string value. In this case, the name of the item should contain the string you searched for.

find() gets a non-reactive result from the query. You use this when you want the results only once and don’t want to subscribe to them.

Build and run the project. Click the Search icon and search for a string. You’ll notice that the list only shows rows that match the string.

the list only shows rows that match the string

Integrating a Document-Oriented Database

There are many document-oriented databases available for Android. Couchbase-lite is one of the most popular. Couchbase is a server-side database and Couchbase-lite is its mobile counterpart.

To learn more about Couchbase-lite and how to integrate it into your app, refer to this tutorial on Couchbase for Android.

Where to Go From Here?

You can download the final project using the Download materials button at the top or bottom of this tutorial.

You’ve created an app that integrates an ORM. It also performs CRUD operations on the database. You’ve also learned how to cancel your subscriptions.

As a further enhancement, try adding a batch delete option, which will allow the user to delete multiple entries at the same time. The user can long-press on a list item and then select multiple other items. Then, they can click on a toolbar item to delete all the selected rows.

As a UI enhancement, try allowing the user to delete a list item by swiping it left or right.

You can learn more about ObjectBox on the ObjectBox website.

Finally, for a much deeper dive into this topic, check out the Saving Data on Android book.

I hope you’ve enjoyed this tutorial! If you have any questions or ideas to share, please join the forum below.