Updating and deleting from your Firebase Database

Nick Skelton
Jul 20, 2017 · 3 min read

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.

firebaseData
.child("users")
.child(firebaseAuth.currentUser!!.uid)
.child("cart")
/users/{userId}/cart
A user with 3 salads in their cart
A simple ListView with our four salads, 3 of which are selected
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)
}
}
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)
}

A Practical Guide to Firebase on Android

Google Firebase is the one stop shop for app development. This publication gives developers tips, tricks and guides to everything that’s possible with Firebase

Nick Skelton

Written by

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

A Practical Guide to Firebase on Android

Google Firebase is the one stop shop for app development. This publication gives developers tips, tricks and guides to everything that’s possible with Firebase