Android10/26/2019

Firebase Firestore Android Tutorial — Store & Retrieve Data in Realtime

Cloud Firestore is one of the most powerful cloud-hosted NoSQL databases provided by Firebase.

It allows Android applications to:

  • Store realtime data
  • Sync across devices
  • Work offline
  • Scale automatically
  • Store structured documents

In this tutorial series, we will learn:

  • Firestore setup
  • Save documents
  • Retrieve documents
  • Realtime listeners
  • Queries
  • Pagination
  • Transactions
  • Subcollections

Firestore Tutorial Series

  • Part 1 – Introduction
  • Part 2 – Preparations & Set Document
  • Part 3 – Get Document
  • Part 4 – SnapshotListener
  • Part 5 – Merge & Update
  • Part 6 – Delete Field & Document
  • Part 7 – Custom Objects
  • Part 8 – Add & Retrieve Multiple Documents
  • Part 9 – Simple Queries
  • Part 10 – Compound Queries
  • Part 11 – OR Queries
  • Part 12 – Pagination
  • Part 13 – DocumentChanges
  • Part 14 – Batched Writes
  • Part 15 – Transactions
  • Part 16 – Arrays
  • Part 17 – Nested Objects
  • Part 18 – Subcollections

What Is Firebase Firestore?

Cloud Firestore is a cloud-hosted realtime NoSQL database provided by Firebase.

Firestore allows developers to:

  • Store structured data
  • Sync data in realtime
  • Build scalable apps
  • Support offline mode
  • Work across multiple platforms

Firestore Data Structure

Firestore stores data using:

  • Collections
  • Documents
  • Fields
  • Subcollections

Firestore Hierarchy


Collection
    └── Document
            └── Fields
                    └── Subcollection

Supported Firestore Data Types

  • String
  • Integer
  • Boolean
  • Timestamp
  • GeoPoint
  • Array
  • Map / Nested Object
  • Binary Data

Why Use Firestore?

  • Realtime synchronization
  • Offline support
  • Automatic scaling
  • Serverless backend
  • Secure Firebase integration
  • Android, iOS, Web support

Firestore vs Realtime Database

Realtime Database Firestore
JSON tree structure Document-based structure
Less scalable queries Advanced querying
Limited indexing Automatic indexing
Older Firebase database Modern Firebase database

Official Firebase Links

Firestore Data Model:

https://firebase.google.com/docs/firestore/data-model

Firestore vs Realtime Database:

https://firebase.google.com/docs/firestore/rtdb-vs-firestore


Part 2 — Setup Firebase Firestore

To use Firestore in Android:

  • Create Firebase project
  • Connect app to Firebase
  • Add Firebase dependencies
  • Initialize Firestore

Modern Firebase Dependency Setup

Inside:


build.gradle

Add:


implementation platform(
'com.google.firebase:firebase-bom:33.1.0'
)

implementation
'com.google.firebase:firebase-firestore'

Important Modernization

Older tutorials use:


android.support.*

which is deprecated.

Modern Android applications should use:


androidx.*

Modern activity_main.xml


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

    xmlns:android=
    "http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:padding="16dp">

    <EditText
        android:id="@+id/edit_text_title"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Title"/>

    <EditText
        android:id="@+id/edit_text_description"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Description"/>

    <Button
        android:id="@+id/button_save"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Save"/>

    <Button
        android:id="@+id/button_load"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Load"/>

    <TextView
        android:id="@+id/text_view_data"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textSize="18sp"/>

</LinearLayout>

Initialize Firestore


FirebaseFirestore db =
        FirebaseFirestore
        .getInstance();

Save Data to Firestore

Firestore stores data inside:

  • Collections
  • Documents

Firestore Save Example


Map<String, Object> note =
        new HashMap<>();

note.put("title", title);

note.put("description", description);

db.collection("Notebook")
        .document("My First Note")
        .set(note);

Understanding Firestore Save Flow

  1. Create collection
  2. Create document
  3. Create fields
  4. Upload document to cloud

Using Success Listener


.addOnSuccessListener(
        unused -> {

        }
)

Triggered when upload succeeds.


Using Failure Listener


.addOnFailureListener(
        e -> {

        }
)

Triggered when upload fails.


Modern Save Example


db.collection("Notebook")
        .document("My First Note")
        .set(note)

        .addOnSuccessListener(
                unused -> {

                    Toast.makeText(
                            this,
                            "Saved",
                            Toast.LENGTH_SHORT
                    ).show();
                }
        )

        .addOnFailureListener(
                e -> {

                    Log.d(
                            "Firestore",
                            e.toString()
                    );
                }
        );

Part 3 — Retrieve Firestore Document

Firestore documents can be retrieved using:


get()

Firestore Document Reference


DocumentReference noteRef =
        db.document(
                "Notebook/My First Note"
        );

Retrieve Document Example


noteRef.get()

.addOnSuccessListener(
        documentSnapshot -> {

            if (
                documentSnapshot.exists()
            ) {

                String title =
                        documentSnapshot
                        .getString("title");

                String description =
                        documentSnapshot
                        .getString(
                                "description"
                        );
            }
        }
);

What Is DocumentSnapshot?

DocumentSnapshot contains:

  • Document data
  • Field values
  • Metadata
  • Existence status

Check If Document Exists


if(documentSnapshot.exists())

Always check document existence before accessing data.


Realtime Firestore Features

Firestore supports:

  • Realtime updates
  • Automatic synchronization
  • Offline caching
  • Live listeners

What Is SnapshotListener?

SnapshotListener listens for realtime document updates.


SnapshotListener Example


noteRef.addSnapshotListener(
        (snapshot, error) -> {

        }
);

Firestore Query Features

Firestore supports:

  • whereEqualTo()
  • whereGreaterThan()
  • orderBy()
  • limit()
  • Pagination

Firestore Security Rules

Firestore security rules protect database access.

Example:


rules_version = '2';

service cloud.firestore {

  match /databases/{database}/documents {

    match /{document=**} {

      allow read, write:
          if request.auth != null;
    }
  }
}

Modern Android Recommendations

Modern Android applications commonly use:

  • MVVM Architecture
  • Repository Pattern
  • Coroutines
  • Flow / LiveData
  • ViewModel
  • Jetpack Compose

Firestore + MVVM Architecture

Recommended structure:


UI
    ↓
ViewModel
    ↓
Repository
    ↓
Firestore

Using Kotlin Coroutines

Modern Firestore apps commonly use:


suspend functions

instead of callbacks.


Common Beginner Mistakes

1. Not Setting Security Rules

Never leave Firestore fully public in production.


2. Storing Large Nested Data

Use subcollections for scalable structures.


3. Ignoring Offline Support

Firestore automatically supports offline persistence.


Best Practices

  • Use collections properly
  • Use document IDs wisely
  • Keep documents small
  • Use indexes for queries
  • Apply secure Firestore rules

FAQ

What is Firestore?

Firestore is Firebase’s modern realtime NoSQL cloud database.


Does Firestore support realtime updates?

Yes. Firestore supports realtime synchronization across devices.


Can Firestore work offline?

Yes. Firestore includes offline caching support.


Conclusion

Firebase Firestore is one of the best cloud databases for modern Android applications.

It provides realtime synchronization, offline support, scalable architecture, and seamless Firebase integration.

Modern Android applications should combine Firestore, MVVM architecture, AndroidX, secure Firestore rules, and scalable backend architecture for production-grade applications.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Deep Structural Diagnostics.

Mastering JSON is only the first step. Use our industrial-grade workbench to format, validate, and synthesize models for your production APIs.