繁体   English   中英

如何使用 Kotlin 在 Android 中使用随机自动生成的 ID 检索 Firebase 节点的值

[英]How can i retrieve values of Firebase Nodes with random auto generated IDs in Android Using Kotlin

我不知道如何从 Firebase 实时数据库中检索数据,其中值具有随机生成的 ID,如下所示。 在此处输入图片说明

为了能够获取21-6-21节点下存在的所有键和值,您需要循环遍历 DatasnaShot 对象,如以下代码行所示:

val rootRef = FirebaseDatabase.getInstance().reference
val dateRef = rootRef.child("SigninData").child("CSC101").child("21-6-21")
val valueEventListener = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        for (ds in dataSnapshot.children) {
            val key = ds.getkey()
            val value = ds.getValue(String::class.java)
            Log.d("TAG", "$key/$value")
        }
    }

    override fun onCancelled(databaseError: DatabaseError) {
        Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
    }
}
dateRef.addListenerForSingleValueEvent(valueEventListener)

logcat 中的结果将是:

-Mf8...ESM/oma@gmail.com...
-Mf8...7nb/oma@gmail.com...
-Mf8...XJv/oma@gmail.com...

编辑:

private fun getDataFrom(date: String) {
    val rootRef = FirebaseDatabase.getInstance().reference
    val dateRef = rootRef.child("SigninData").child("CSC101").child(date)
    val valueEventListener = object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
            for (ds in dataSnapshot.children) {
                val key = ds.getkey()
                val value = ds.getValue(String::class.java)
                Log.d("TAG", "$key/$value")
            }
        }

        override fun onCancelled(databaseError: DatabaseError) {
            Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
        }
    }
    dateRef.addListenerForSingleValueEvent(valueEventListener)
}

现在您可以使用以下任一方法调用上述方法:

getDataFrom("21-6-21")

要么:

getDataFrom("22-6-21")

如果您需要同时获取它们,那么您应该使用 get() 调用,并将两个 Task 对象传递给whenAllSuccess(Task...<?> tasks)

我相信这对你有用。

    fun getDataFromFirebaseDatabase() {
        // Your path 
        database.getReference("SigninData/CSC101/21-6-21")
            .get()
            .addOnCompleteListener {
                //this checks if there were any exceptions or Errors generated and will Log the error in your Logcat.
                if (it.exception != null) Log.e("FirebaseDatabase", "Error", it.exception)
                // this checks if your result was successful or not and also, 
                //if it has children or not, if both conditions are satisfied,
                //it will enter the for loop and print all the
                // values along with their keys in logcat.
                if (it.isSuccessful && it.result.hasChildren()) {
                    for (i in it.result.children) {
                        //i.key will give you required key
                        Log.d("FirebaseDatabase", "key is ${i.key}")
                        // i.value will give respective value
                        // import the values as given in database, for your case it would be String so.
                        val data = i.value as String
                        Log.d("FirebaseDatabase", "value is $data")
                    }
                }
            }
    }

注意 - 这将读取 21-6-21 子项中的所有值

您的 Logcat 应该看起来像这样。

//if there is an error
E/FirebaseDatabase: Error <Some Error Code Here>

//if Run is Successful
//since there are 3 entries in CSC101 node all three will be printed one by one
//like the example given below

D/FirebaseDatabase: key is Mf80wSd9neOAqlPhESM
D/FirebaseDatabase: value is oma@gmail.com You signed in for CSC101

上面的代码使用get()函数,这意味着您的应用程序只会读取数据库一次。 除了 get() 您还可以使用:

  1. addChildEventListener()
  2. addValueEventListener()
  3. addListenerForSingleValueEvent()

都是为了不同的目的。 以下是有关这些的 Firebase 文档: https ://firebase.google.com/docs/database/android/read-and-write#read_data

第 3 个函数类似于 get 函数,但第 3 个函数将从缓存中读取,并且应该在您不希望数据频繁更改时使用。

一旦数据库节点发生更改,第一个和第二个将从数据库中获取结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM