Back to Blog

Initialize Firestore and save a post to the database

Sandy LaneSandy Lane

Video: Initialize Firestore and save a post to the database by Taught by Celeste AI - AI Coding Coach

Watch full page →

Initialize Firestore and Save a Post to the Database

In this tutorial, you'll learn how to set up Firebase Firestore in your Android project using Jetpack components and save a simple post object to the database. We'll cover initializing Firestore, creating a data model, and writing data asynchronously to Firestore.

Code

import com.google.firebase.firestore.FirebaseFirestore

// Data class representing a Post
data class Post(
  val title: String = "",
  val content: String = ""
)

fun savePostToFirestore() {
  // Initialize Firestore instance
  val db = FirebaseFirestore.getInstance()

  // Create a new post object
  val post = Post(
    title = "Hello Firestore",
    content = "This is a post saved from my Android app."
  )

  // Add a new document with a generated ID to the "posts" collection
  db.collection("posts")
    .add(post)
    .addOnSuccessListener { documentReference ->
      println("Post saved with ID: ${documentReference.id}")
    }
    .addOnFailureListener { e ->
      println("Error adding post: $e")
    }
}

Key Points

  • Initialize Firestore by calling FirebaseFirestore.getInstance() in your Android app.
  • Create a data class to represent the structure of the data you want to save.
  • Use the collection() method to specify the Firestore collection and add() to save a new document.
  • Handle success and failure asynchronously with addOnSuccessListener and addOnFailureListener.
  • Firestore automatically generates unique document IDs when using add() without specifying an ID.