DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Programming Solutions for Graph and Data Structure Problems With Implementation Examples (Word Dictionary)
  • Testcontainers With Kotlin and Spring Data R2DBC
  • Leveraging Change Data Capture for Fraud Detection using Arcion Cloud
  • Building a Kotlin Mobile App With the Salesforce SDK: Editing and Creating Data

Trending

  • Reflections From a DBA
  • Navigating the Skies
  • What You Must Know About Rate Limiting
  • A Better Web3 Experience: Account Abstraction From Flow (Part 2)
  1. DZone
  2. Data Engineering
  3. Data
  4. Storing and Retrieving Data From Firebase With Kotlin on Android

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.

Nick Skelton user avatar by
Nick Skelton
·
Jul. 17, 17 · Tutorial
Like (0)
Save
Tweet
Share
23.46K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Data (computing) Firebase Database design Android (robot) Kotlin (programming language)

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

Opinions expressed by DZone contributors are their own.

Related

  • Programming Solutions for Graph and Data Structure Problems With Implementation Examples (Word Dictionary)
  • Testcontainers With Kotlin and Spring Data R2DBC
  • Leveraging Change Data Capture for Fraud Detection using Arcion Cloud
  • Building a Kotlin Mobile App With the Salesforce SDK: Editing and Creating Data

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: