Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

How to Create and Add Data to Firebase Firestore in Android?

Firebase Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud. To create and add data to Firebase Firestore in an Android application, follow these steps:

1. Setup Firebase Firestore:

  1. Go to the Firebase Console and create a new project (or select an existing project).
  2. In the Firebase console, click on "Database" in the left sidebar, and then click on "Create Database" to initiate Firestore in either production or test mode.
  3. Go to Project Settings > Add App and select the Android icon to add an Android app to your Firebase project.
  4. Register your app by providing your app's package name and other details.
  5. Download the google-services.json file and place it in the app directory of your Android project.

2. Add Firebase SDK to Your App:

In your project-level build.gradle file:

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.x.x' // Check for the latest version
    }
}

In your app-level build.gradle file:

dependencies {
    // ...
    implementation 'com.google.firebase:firebase-firestore:24.x.x' // Check for the latest version
}

// Apply the Google services plugin at the bottom of the file
apply plugin: 'com.google.gms.google-services'

Sync your Gradle files.

3. Create and Add Data:

To add data to Firestore:

// Initialize Firestore
val db = Firebase.firestore

// Create a new user with a first and last name
val user = hashMapOf(
    "first" to "John",
    "last" to "Doe",
    "born" to 1980
)

// Add a new document with a generated ID
db.collection("users")
    .add(user)
    .addOnSuccessListener { documentReference ->
        Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "Error adding document", e)
    }

In the example above:

  • We're initializing Firebase Firestore.
  • We're creating a HashMap with some user data.
  • We're adding this data to the Firestore under the users collection.

Remember that Firestore is NoSQL, so you don't need to predefine tables or structures. Collections and documents can be created on the fly.

Security:

Always ensure that your Firestore rules are set correctly, especially if you're using Firestore in a production app. The default rules may prevent reading/writing if you haven't configured them yet. Proper Firestore rules can help you prevent unauthorized access and secure user data.

With Firestore, you can efficiently build real-time databases for your apps, integrate with authentication, cloud functions, and more.

  1. Adding data to Firestore in Android Kotlin:

    • Description: Firestore is a NoSQL document database provided by Firebase. Adding data involves creating a reference to a Firestore collection and adding a document with the desired data.
    • Code (Kotlin):
      // Example of adding data to Firestore
      val db = FirebaseFirestore.getInstance()
      val collectionReference = db.collection("users")
      
      val user = hashMapOf(
          "name" to "John Doe",
          "email" to "john@example.com"
      )
      
      collectionReference.add(user)
          .addOnSuccessListener { documentReference ->
              // Data added successfully
              Log.d("Firestore", "Document added with ID: ${documentReference.id}")
          }
          .addOnFailureListener { e ->
              // Handle errors
              Log.e("Firestore", "Error adding document", e)
          }
      
  2. Creating a Firestore collection in Android:

    • Description: Collections in Firestore are containers for documents. You can create a new collection by referencing it and then adding documents to it.
    • Code (Kotlin):
      // Example of creating a Firestore collection
      val db = FirebaseFirestore.getInstance()
      val collectionReference = db.collection("books")
      
      // Add documents to the "books" collection
      
  3. Firestore document creation in Android example:

    • Description: Firestore documents contain fields and data. You can create a document by adding key-value pairs representing the fields and their values.
    • Code (Kotlin):
      // Example of creating a Firestore document
      val db = FirebaseFirestore.getInstance()
      val collectionReference = db.collection("cities")
      
      val city = hashMapOf(
          "name" to "New York",
          "population" to 8419600
      )
      
      collectionReference.add(city)
          .addOnSuccessListener { documentReference ->
              // Document added successfully
              Log.d("Firestore", "Document added with ID: ${documentReference.id}")
          }
          .addOnFailureListener { e ->
              // Handle errors
              Log.e("Firestore", "Error adding document", e)
          }
      
  4. Handling Firestore transactions in Android:

    • Description: Firestore transactions ensure the consistency of data by performing a series of reads and writes atomically. This is useful for scenarios where multiple users may be modifying the same data.
    • Code (Kotlin):
      // Example of a Firestore transaction
      val db = FirebaseFirestore.getInstance()
      val docRef = db.collection("cities").document("SF")
      
      db.runTransaction { transaction ->
          val snapshot = transaction.get(docRef)
          val newPopulation = snapshot.getLong("population")!! + 1
          transaction.update(docRef, "population", newPopulation)
      }
      .addOnSuccessListener {
          Log.d("Firestore", "Transaction success!")
      }
      .addOnFailureListener { e ->
          // Handle errors
          Log.e("Firestore", "Transaction failure", e)
      }
      
  5. Firebase Firestore real-time updates in Android:

    • Description: Firestore provides real-time updates, allowing your app to receive live updates when the data changes. You can listen for changes in a document or a query result set.
    • Code (Kotlin):
      // Example of real-time updates in Firestore
      val db = FirebaseFirestore.getInstance()
      val docRef = db.collection("cities").document("SF")
      
      docRef.addSnapshotListener { snapshot, e ->
          if (e != null) {
              // Handle errors
              Log.e("Firestore", "Listen failed", e)
              return@addSnapshotListener
          }
      
          if (snapshot != null && snapshot.exists()) {
              Log.d("Firestore", "Current data: ${snapshot.data}")
          } else {
              Log.d("Firestore", "Current data: null")
          }
      }