简体   繁体   English

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

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

I don't know how to go about retrieving data from the Firebase Realtime Database where the values have randomly generated IDs as seen below.我不知道如何从 Firebase 实时数据库中检索数据,其中值具有随机生成的 ID,如下所示。 在此处输入图片说明

To be able to get all the keys and values that exist under the 21-6-21 node, you need to loop through the DatasnaShot object, as in the following lines of code:为了能够获取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)

The result in the logcat will be: logcat 中的结果将是:

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

Edit:编辑:

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)
}

Now you can call the above method either with:现在您可以使用以下任一方法调用上述方法:

getDataFrom("21-6-21")

Or:要么:

getDataFrom("22-6-21")

If you need to get them both, then you should use a get() call, and pass both Task objects to the whenAllSuccess(Task...<?> tasks) .如果您需要同时获取它们,那么您应该使用 get() 调用,并将两个 Task 对象传递给whenAllSuccess(Task...<?> tasks)

I believe this will work out for you.我相信这对你有用。

    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")
                    }
                }
            }
    }

Note - This will read all the values inside 21-6-21 child注意 - 这将读取 21-6-21 子项中的所有值

Your Logcat should look something like this.您的 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

The above code uses get() function which means your app will only read the database only once.上面的代码使用get()函数,这意味着您的应用程序只会读取数据库一次。 Instead of get() you can also use:除了 get() 您还可以使用:

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

All are for different purposes.都是为了不同的目的。 Here are the Firebase Docs regarding these: https://firebase.google.com/docs/database/android/read-and-write#read_data以下是有关这些的 Firebase 文档: https ://firebase.google.com/docs/database/android/read-and-write#read_data

the 3rd one is similar to the get function but 3rd one will read from the cache memory and should be used when you are not expecting your data to change frequently.第 3 个函数类似于 get 函数,但第 3 个函数将从缓存中读取,并且应该在您不希望数据频繁更改时使用。

1st and 2nd will get the results from the database as soon as there are changes made in the database nodes.一旦数据库节点发生更改,第一个和第二个将从数据库中获取结果。

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

相关问题 如何从Firebase到Android的Listview中检索所有节点数据? - How can I retrieve all nodes data from Firebase to listview in Android? 如何从 Firebase 中的多个节点检索数据? Android - How do I retrieve data from multiple nodes in Firebase? Android 如何在Firebase中检索唯一键的所有子节点 - How can i retrieve all child nodes of unique key in Firebase 如何在Android中为生成的视图添加唯一ID? - How can I add unique IDs to generated views in Android? 如何从Firebase数据库检索随机值? - How can I retrieve a random value from Firebase database? 如何在 Android Studio 中使用来自 Firebase 数据库的查询在不使用唯一 ID 的情况下获取子节点? - How to Fetch child nodes without using unique ids using Query from Firebase database in Android Studio? 如何使用Firebase数据库中的Datasnapshot获取多个节点的多个值? - How can i get Multiple values of multiple nodes using Datasnapshot from the Firebase Database? 如何检索自动生成的 ID 以删除 firebase 中的数据 - how do you retrieve a auto generated id to delete data in firebase Android Kotlin:如何从 Firebase 中删除数据 - Android Kotlin: How can I delete the data from Firebase 如何使用 Android Studio 简单地检索 Firebase 中的所有项目和值 - How to Simply retrieve all the items and values in Firebase using Android Studio
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM