Updating and deleting from your Firebase Database

Nick Skelton
A Practical Guide to Firebase on Android
3 min readJul 20, 2017

A simple getting started guide to Firebase Database, a NoSQL database with a rich client side API.

We’ve seen how to create and retrieve data from our Firebase database using some simple code to populate our database with a bunch of salads. So now we will create a shopping cart for our users to demonstrate updating and deleting data in realtime.

Recall the post on Firebase Authentication. Remember Anonymous users? Utilising the idea of anonymous users, your app should always be either logged in as a real user or an anonymous user. This means that you always have access to a Unique User Id.

We will use this value to create a new node in our Firebase database

firebaseData
.child("users")
.child(firebaseAuth.currentUser!!.uid)
.child("cart")

If you are used to REST, this translates to something like this

/users/{userId}/cart

Into our cart, we want to put Salads. But we don’t want to copy the entire Salad object into the cart, just the ID of the Salad so that we get this in the Firebase Database console:

A user with 3 salads in their cart

Notice the three entries under cart, this corresponds to the app below:

A simple ListView with our four salads, 3 of which are selected

To add and delete from our shopping cart is simple:

private const val USERS = "users"
private const val CART = "cart"

class ShoppingCart {

private var firebaseData = FirebaseDatabase.getInstance().reference

fun addItem(userId: String, shopItemId: String) {
firebaseData
.child(USERS)
.child(userId)
.child(CART)
.child(shopItemId)
.setValue(true)
}

fun removeItem(userId: String, shopItemId: String) {
firebaseData
.child(USERS)
.child(userId)
.child(CART)
.child(shopItemId)
.setValue(null)
}
}

This is great for updating our shopping cart, but we also want to watch our shopping cart so that we can make changes on screen to synchronise with these persistent changes. We do this by using the new paradigm in Firebase Database addListener to setup a real time connection to the nodes of our database that are of immediate interest to us.

private fun initShoppingCartListener() {
val cartListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
button_buy.text = "Buy ${dataSnapshot.childrenCount} items"
}

override fun onCancelled(databaseError: DatabaseError) {
println("shopping cart changed listener failed:onCancelled ${databaseError.toException()}")
}
}

firebaseData
.child("users")
.child(firebaseAuth.currentUser!!.uid)
.child("cart").addValueEventListener(cartListener)
}

Here I have created a ValueEventListener to listen for changes to the current user’s shopping cart. All it does is count the number of items in the cart and updates the button on screen.

At first, it seemed a little clunky, a lot of code for simply retrieving a little bit of data. But the cool thing about this ValueEventListener paradigm is the connection from UI to backend is seamless. Put your phone into Airplane Mode, go into the console, delete some entries manually from the shopping cart, take your phone off Airplane Mode, and the listener picks up the change.

That is the power of the realtime database at work.

--

--

Nick Skelton
A Practical Guide to Firebase on Android

Freelance Android Dev. Google Developer Expert. Full Time Remote. Part Time Buzzword Hacker.