Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Storing and Retrieving Data From Firebase With Kotlin on Android

DZone's Guide to

Storing and Retrieving Data From Firebase With Kotlin on Android

The Firebase Database API lets you use the real-time features of NoSQL for smooth and responsive data retrieval in your Android application.

· Mobile Zone
Free Resource

Get gorgeous, multi-touch charts for your iOS application with just a few lines of code.

The Firebase Database API focuses on the powerful real-time 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 real-time 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.

Denormalization 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:

Image title

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.

.Net developers: use Highcharts, the industry's leading interactive charting library, without writing a single line of JavaScript.

Topics:
mobile ,firebase ,kotlin ,android ,mobile app development

Published at DZone with permission of Nick Skelton, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}