Bird
Raised Fist0
Android Kotlinmobile~20 mins

Cloud Firestore integration in Android Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Firestore Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
Firestore Data Display Update

You have a Firestore collection named users. You want to display the name field of each user in a RecyclerView. Which code snippet correctly listens for real-time updates and updates the UI?

Android Kotlin
val db = FirebaseFirestore.getInstance()
db.collection("users")
  .addSnapshotListener { snapshots, e ->
    if (e != null) {
      Log.w("Firestore", "Listen failed.", e)
      return@addSnapshotListener
    }
    val userList = mutableListOf<String>()
    for (doc in snapshots!!.documents) {
      userList.add(doc.getString("name") ?: "Unknown")
    }
    // update RecyclerView adapter here with userList
  }
A
db.collection("users").addSnapshotListener { snapshots, e -&gt;
  if (e != null) return@addSnapshotListener
  val userList = mutableListOf&lt;String&gt;()
  for (doc in snapshots!!.documents) {
    userList.add(doc.getString("name") ?: "Unknown")
  }
  // update RecyclerView adapter here
}
B
db.collection("users").get().addOnSuccessListener { result -&gt;
  val userList = result.map { it.getString("name") ?: "Unknown" }
  // update RecyclerView adapter here
}
C
db.collection("users").addSnapshotListener { snapshots, e -&gt;
  if (e != null) return@addSnapshotListener
  val userList = snapshots!!.map { it.getString("name") ?: "Unknown" }
  // update RecyclerView adapter here
}
D
db.collection("users").addSnapshotListener { snapshots, e -&gt;
  if (e != null) return@addSnapshotListener
  val userList = mutableListOf&lt;String&gt;()
  for (doc in snapshots!!) {
    userList.add(doc.getString("email") ?: "Unknown")
  }
  // update RecyclerView adapter here
}
Attempts:
2 left
💡 Hint

Remember that addSnapshotListener provides real-time updates and you must check for errors before processing data.

🧠 Conceptual
intermediate
1:30remaining
Firestore Document Write Behavior

What happens if you call set() on a Firestore document that already exists without specifying SetOptions.merge()?

AThe write operation is ignored and the document remains unchanged.
BThe new data is merged with the existing document fields automatically.
CFirestore throws a runtime exception because the document exists.
DThe existing document is completely overwritten with the new data.
Attempts:
2 left
💡 Hint

Think about whether set() replaces or merges data by default.

❓ lifecycle
advanced
2:00remaining
Firestore Listener Memory Leak

You added a Firestore addSnapshotListener in your Activity's onCreate() method. What is the best practice to avoid memory leaks related to this listener?

ARemove the listener in the Activity's <code>onDestroy()</code> method by calling <code>remove()</code> on the listener registration.
BNo action needed; Firestore listeners automatically stop when the Activity is destroyed.
CCall <code>remove()</code> on the listener registration in the Activity's <code>onPause()</code> method only.
DSet the listener variable to null in <code>onStop()</code> to release resources.
Attempts:
2 left
💡 Hint

Think about how to properly clean up listeners to prevent leaks.

📝 Syntax
advanced
1:30remaining
Correct Firestore Query Syntax

Which of the following Kotlin Firestore queries correctly retrieves documents from the orders collection where the status field equals "shipped" and orders the results by date descending?

Adb.collection("orders").orderBy("date", Query.Direction.DESCENDING).whereEqualTo("status", "shipped").get()
Bdb.collection("orders").whereEqualTo("status", "shipped").orderBy("date", Query.Direction.DESCENDING).get()
Cdb.collection("orders").whereEqualTo("status", "shipped").orderBy("date", "DESC").get()
Ddb.collection("orders").where("status" == "shipped").orderBy("date", Query.Direction.DESCENDING).get()
Attempts:
2 left
💡 Hint

Check the order of method calls and parameter types for orderBy.

🔧 Debug
expert
2:30remaining
Firestore Security Rules Blocking Access

Your Android app tries to read documents from Firestore but always gets a permission denied error. Your security rules are:

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read: if request.auth.uid == userId;
    }
  }
}

Your app calls db.collection("users").get() to read all users. Why does this fail?

AThe rules syntax is invalid and Firestore rejects all reads.
BThe app is not authenticated, so all reads are denied by default.
CThe rules only allow reading documents where the document ID matches the authenticated user ID, so reading the whole collection is denied.
DThe app must use <code>getDocument()</code> instead of <code>get()</code> to read documents.
Attempts:
2 left
💡 Hint

Consider how the rules restrict access by document ID and user ID.

Practice

(1/5)
1. What is the primary purpose of Cloud Firestore in an Android app?
easy
A. To compile Kotlin code
B. To design the app's user interface
C. To store and sync app data in the cloud
D. To manage app permissions

Solution

  1. Step 1: Understand Cloud Firestore's role

    Cloud Firestore is a cloud database service that stores and syncs app data.
  2. Step 2: Differentiate from other app functions

    UI design, code compilation, and permission management are handled by other tools, not Firestore.
  3. Final Answer:

    To store and sync app data in the cloud -> Option C
  4. Quick Check:

    Cloud Firestore = Data storage and sync [OK]
Hint: Remember Firestore is a cloud database, not UI or code tool [OK]
Common Mistakes:
  • Confusing Firestore with UI design tools
  • Thinking Firestore compiles code
  • Assuming Firestore manages app permissions
2. Which Kotlin code correctly initializes a Firestore instance?
easy
A. val db = FirebaseFirestore.getInstance()
B. val db = Firestore.getInstance()
C. val db = Firebase.getFirestore()
D. val db = FirestoreClient.get()

Solution

  1. Step 1: Recall Firestore initialization syntax

    The official way to get Firestore instance in Kotlin is FirebaseFirestore.getInstance().
  2. Step 2: Check other options for correctness

    Other options use incorrect class or method names not in Firestore API.
  3. Final Answer:

    val db = FirebaseFirestore.getInstance() -> Option A
  4. Quick Check:

    Correct Firestore init = val db = FirebaseFirestore.getInstance() [OK]
Hint: Use FirebaseFirestore.getInstance() to start Firestore [OK]
Common Mistakes:
  • Using Firestore.getInstance() which does not exist
  • Confusing FirebaseFirestore with Firebase class
  • Using FirestoreClient which is not part of Android SDK
3. Given this code snippet, what will be printed if the document exists with field "name" = "Alice"?
val db = FirebaseFirestore.getInstance()
db.collection("users").document("user1").get()
  .addOnSuccessListener { document ->
    if (document != null && document.exists()) {
      println(document.getString("name"))
    } else {
      println("No such document")
    }
  }
medium
A. Alice
B. No such document
C. null
D. Error at runtime

Solution

  1. Step 1: Understand the get() and success listener

    The get() fetches the document asynchronously; if it exists, the listener runs the success block.
  2. Step 2: Check document existence and print field

    Since document exists and has "name" = "Alice", println(document.getString("name")) prints "Alice".
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    Document exists with name = Alice [OK]
Hint: If document exists, getString returns the field value [OK]
Common Mistakes:
  • Assuming document is null when it exists
  • Expecting 'No such document' incorrectly
  • Confusing getString with get() returning document
4. Identify the error in this Firestore write operation:
val db = FirebaseFirestore.getInstance()
db.collection("users").document("user1").set("name", "Bob")
medium
A. document() must be called after set()
B. Collection name cannot be "users"
C. FirebaseFirestore.getInstance() is incorrect
D. set() requires a Map or an object, not two parameters

Solution

  1. Step 1: Check set() method signature

    set() expects a single argument: a Map or an object representing fields and values.
  2. Step 2: Analyze the provided code

    Passing two parameters "name", "Bob" is invalid and causes a compile error.
  3. Final Answer:

    set() requires a Map or an object, not two parameters -> Option D
  4. Quick Check:

    set() needs one argument (Map/object) [OK]
Hint: Use a Map for set(), not separate key-value parameters [OK]
Common Mistakes:
  • Passing multiple parameters to set() instead of a Map
  • Calling document() after set() instead of before
  • Thinking collection name restrictions cause error
5. You want to listen in real-time to changes in a Firestore collection "messages" and update your UI accordingly. Which code snippet correctly sets up this listener?
hard
A. db.collection("messages").get().addOnSuccessListener { snapshots -> for (doc in snapshots) { println(doc.getString("text")) } }
B. db.collection("messages").addSnapshotListener { snapshots, e -> if (e != null) { println("Listen failed") } else { for (doc in snapshots!!) { println(doc.getString("text")) } } }
C. db.collection("messages").document().addSnapshotListener { doc, e -> println(doc?.getString("text")) }
D. db.collection("messages").addListener { snapshots -> println(snapshots) }

Solution

  1. Step 1: Understand real-time listeners in Firestore

    addSnapshotListener listens for real-time updates on a collection or document.
  2. Step 2: Analyze each option

    db.collection("messages").addSnapshotListener { snapshots, e -> if (e != null) { println("Listen failed") } else { for (doc in snapshots!!) { println(doc.getString("text")) } } } correctly uses addSnapshotListener on collection with error check and iterates snapshots. db.collection("messages").get().addOnSuccessListener { snapshots -> for (doc in snapshots) { println(doc.getString("text")) } } uses get() which is one-time fetch. db.collection("messages").document().addSnapshotListener { doc, e -> println(doc?.getString("text")) } listens on a document without specifying ID. db.collection("messages").addListener { snapshots -> println(snapshots) } uses non-existent addListener method.
  3. Final Answer:

    db.collection("messages").addSnapshotListener { snapshots, e -> if (e != null) { println("Listen failed") } else { for (doc in snapshots!!) { println(doc.getString("text")) } } } -> Option B
  4. Quick Check:

    Real-time listener = addSnapshotListener on collection [OK]
Hint: Use addSnapshotListener on collection for real-time updates [OK]
Common Mistakes:
  • Using get() instead of addSnapshotListener for real-time
  • Calling addSnapshotListener on document without ID
  • Using non-existent addListener method
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard