如何基于Kotlin中的键值从Firebase读取数据 [英] How to read data from firebase based on a key value in Kotlin

查看:131
本文介绍了如何基于Kotlin中的键值从Firebase读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Kotlin和android studio从firebase检索数据. 这是我的数据类,用于将数据上传到Firebase:

I want to retrieve data from firebase using Kotlin and android studio. This is my data class which is used to upload data into firebase:

class Data(var id : String,
           var productname : String , 
           var username : String,
           var phonenumber : String,
           var address: String,
           var status: String)

要向Firebase添加数据,我使用以下格式:

To add data to firebase, I used the following format:

val ref = FirebaseDatabase.getInstance().getReference("orders")

val orderId :String = ref.push().key.toString()

val formdata = Data(orderId,
                    productname, 
                    username, 
                    phonenumber, 
                    useraddress, 
                    status)

ref.child(orderId).setValue(formdata).addOnCompleteListener {
            Toast.makeText(applicationContext,"Order placed sucessfully", Toast.LENGTH_SHORT).show()
        }

现在,我想从Firebase检索数据,其中电话号码的值与给定的字符串匹配.

Now I want to retrieve data from firebase where the value of phone number matches the given string.

推荐答案

现在,我想从Firebase检索数据,其中电话号码的值与给定的字符串匹配.

Now I want to retrieve data from firebase where the value of phone number matches the given string.

要解决此问题,您需要使用查询,例如以下代码行:

To solve this, you need to use a query, like in the following lines of code:

val rootRef = FirebaseDatabase.getInstance().reference
val ordersRef = rootRef.child("orders").orderByChild("phonenumber").equalTo(givenString)
val valueEventListener = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        for (ds in dataSnapshot.children) {
            val username = ds.child("username").getValue(String::class.java)
            Log.d(TAG, username)
        }
    }

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

logcat中的结果将是电话号码等于给定字符串的订单中存在的用户名.

The result in your logcat, will be the user name that exist in the orders where the phone number is equal to a given string.

这篇关于如何基于Kotlin中的键值从Firebase读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆