Storing and retrieving data from Firebase with Kotlin on Android

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

A short simple guide to using Firebase’s RealTime NoSQL database from your Android app using Kotlin.

The Firebase Database Api focuses on the powerful realtime features of NoSQL. Clearly Google is responding the new expectations of users with perpetually connected mobiles and the interactions that go with that. The most simple example is — comments and chats.

For those who have seen the age old onSuccess() and onFail() interfaces the paradigm shift won’t be difficult to swallow. The benefit of the realtime aspect is that all the underlying notification of changing data is done for you. Once you know what to expect from the API, you can give your users the smooth responsiveness that they expect.

Before you get started with NoSQL, it helps to be already intimate with JSON. Once you understand the structure and syntax of JSON, read the guide to structuring your data on the Firebase website. If you are new to NoSQL, there are plenty of new concepts that you got for free when using SQL and it’s time to adjust.

Denormalisation is often one of the areas that developers new to NoSQL struggle. Duplicating data may seem counterintuitive at first, but it is a necessary evil for the purposes of scaling. There are several ways to do this but let’s save database design for another day (or night) when there is more coffee at hand.

So let’s jump in and have a look at saving and retrieving some data. The Firebase console has a great rear view mirror, for watching what is happening at your backend ;).

Lets take a simple Salad class,

data class Salad(
val name: String = "",
val description: String = "",
var uuid: String = "")

and create some salads and shove them into our Firebase database.

fun loadDatabase(firebaseData: DatabaseReference) {
val availableSalads: List<Salad> = mutableListOf(
Salad("Gherkin", "Fresh and delicious"),
Salad("Lettuce", "Easy to prepare"),
Salad("Tomato", "Boring but healthy"),
Salad("Zucchini", "Healthy and gross")
)
availableSalads.forEach {
val key = firebaseData.child("salads").push().key
it.uuid = key
firebaseData.child("salads").child(key).setValue(it)
}
}

The data appears in our console looking like this:

Our Salad catalogue

Notice that I have used push to obtain a new key from the node then saved it as part of the Salad object before saving the object into the database. This will make referencing the salad within the code much easier later on. There are other ways to do this that make your data a little easier to understand such as using the name property as the key (after cleaning it).

Now, when the Salad App is first opened, we will populate a simple List called menu with the salads in our Firebase Database:

private fun initSaladMenu() {
val menuListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
menu.clear()
dataSnapshot.children.mapNotNullTo(menu) { it.getValue<Salad>(Salad::class.java) }
}

override fun onCancelled(databaseError: DatabaseError) {
println("loadPost:onCancelled ${databaseError.toException()}")
}
}
firebaseData.child("salads").addListenerForSingleValueEvent(menuListener)
}

Notice the familiar onSuccess and onFail pattern? Firebase uses the same idea, but different names: onDataChanged and onCancelled. Here we are introduced to the realtime aspect of Firebase. addListener is used to ‘listen’ to changes in the remote database, rather than just asking for them once. This allows your app to seamlessly connect with anything that is capable of changing your database — websites, web services, other apps...

In our case, we have used addListenerForSingleValueEvent because we aren’t interested in changes to this data. I don’t expect the menu to change often so there is no need to waste resources listening to this section of the database.

So have just queried the salads node, cast the response back into a mutable list:

private val menu: MutableList<Salad> = mutableListOf()

This covers storing and retrieving data. Next up, we will create a simple shopping cart for our users to save their salads in, demonstrating the powerful combination of Firebase Users and Database used in conjunction with one another.

--

--

Nick Skelton
A Practical Guide to Firebase on Android

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