Read and Write Data on Android

This document covers the basics of reading and writing Firebase data.

Firebase data is written to a FirebaseDatabase reference and retrieved by attaching an asynchronous listener to the reference. The listener is triggered once for the initial state of the data and again anytime the data changes.

(Optional) Prototype and test with Firebase Local Emulator Suite

Before talking about how your app reads from and writes to Realtime Database, let's introduce a set of tools you can use to prototype and test Realtime Database functionality: Firebase Local Emulator Suite. If you're trying out different data models, optimizing your security rules, or working to find the most cost-effective way to interact with the back-end, being able to work locally without deploying live services can be a great idea.

A Realtime Database emulator is part of the Local Emulator Suite, which enables your app to interact with your emulated database content and config, as well as optionally your emulated project resources (functions, other databases, and security rules).

Using the Realtime Database emulator involves just a few steps:

  1. Adding a line of code to your app's test config to connect to the emulator.
  2. From the root of your local project directory, running firebase emulators:start.
  3. Making calls from your app's prototype code using a Realtime Database platform SDK as usual, or using the Realtime Database REST API.

A detailed walkthrough involving Realtime Database and Cloud Functions is available. You should also have a look at the Local Emulator Suite introduction.

Get a DatabaseReference

To read or write data from the database, you need an instance of DatabaseReference:

Kotlin

private lateinit var database: DatabaseReference
// ...
database = Firebase.database.reference.kt