You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

安卓Firebase开发:Swift获取用户列表代码转Android实现求助

Converting Swift Firebase User Fetch to Android (Kotlin)

Hey there! Since you’re making the jump from Swift to Android, let’s walk through translating your Firebase Realtime Database code into Kotlin. The goal here is to fetch all users from the "Users" node (ordered by the "Name" field) and store them in a string array (or a list, which is more commonly used in Kotlin for dynamic collections).

Step-by-Step Breakdown

First, make sure you’ve got Firebase Realtime Database set up in your Android project (add dependencies, configure google-services.json—you know the drill!). Then let’s dive into the code:

1. Reference the Database Node

In Swift, you used Database.database().reference()—in Android, this translates to FirebaseDatabase.getInstance().reference. We’ll point this to the "Users" node and create a query ordered by the "Name" field, just like your Swift code.

2. Fetch Data Once

Instead of observeSingleEvent(of: .value), Android uses addListenerForSingleValueEvent—this does the exact same thing: fetches the data one time without listening for future updates.

3. Iterate Through the Snapshot

The snapshot in Android has a children property we can loop through. For each child, we’ll extract the user’s name (or whatever string value you need) and add it to our collection.

4. Convert to a String Array

Kotlin prefers MutableList<String> for dynamic lists, but we can easily convert it to a String[] if you specifically need an array.

Full Kotlin Code

import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener

fun fetchUsersIntoStringArray() {
    // Get reference to the Firebase Realtime Database
    val database: DatabaseReference = FirebaseDatabase.getInstance().reference
    // Create query for "Users" node, ordered by "Name" field
    val userQuery = database.child("Users").orderByChild("Name")

    // Fetch data once
    userQuery.addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            val userNamesList = mutableListOf<String>()
            
            // Loop through each user snapshot in the "Users" node
            for (childSnapshot in snapshot.children) {
                // Extract the "Name" value (adjust if you need a different string field)
                val userName = childSnapshot.child("Name").getValue(String::class.java)
                // Safely add to list only if the name isn't null
                userName?.let { userNamesList.add(it) }
            }
            
            // Convert the list to a string array if needed
            val userNamesArray = userNamesList.toTypedArray()
            
            // Use the array here! (e.g., update UI, process data)
            // Note: This runs on the main thread, so you can update UI directly
        }

        override fun onCancelled(error: DatabaseError) {
            // Handle any errors (e.g., log the issue)
            println("Failed to fetch users: ${error.message}")
        }
    })
}

Quick Tips for Swift Developers

  • Asynchronous Flow: Just like in Swift, Firebase calls are async. All code that uses the user array/list needs to run inside the onDataChange block—you can’t access the array outside of it right away.
  • Null Safety: Kotlin enforces null safety, so we use ?.let to make sure we only add non-null names to our list.
  • Collections: MutableList is Kotlin’s equivalent of Swift’s mutable Array. If you need a fixed-size array, toTypedArray() converts the list to a String[].

If you need to map to a custom User object instead of just storing names, let me know—I can share that example too!

内容的提问来源于stack exchange,提问作者David OUIZEMAN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:17:51