【问题标题】:Firebase getting String Value Always Return NullFirebase 获取字符串值总是返回 Null
【发布时间】:2021-07-16 02:03:45
【问题描述】:

我试图获取用户朋友的密钥或 ID,然后向他们所有人发送通知,但是当我重视他们时

这是我的代码

val shared = requireActivity().getSharedPreferences("user_phone", Context.MODE_PRIVATE)
        val currentUserphone = shared.getString("phone","default_value")
        Log.d("friendId", "currentUserphone"+""+currentUserphone)

        val ref = Firebase.database.reference.child("users").child(currentUserphone!!)
            .child("friends").addValueEventListener(object : ValueEventListener{
                override fun onDataChange(snapshot: DataSnapshot) {
                    if (snapshot.exists()) {
                        for (i in snapshot.children) {
                            //val model = snapshot.getValue(friendsIdsModel::class.java)
                            val id = snapshot.child("phone").getValue(String::class.java)
                            //idsList.add(model!!)
                           sendNotifcatiosToFriends(id!!)
                            Log.d("friendId", "fried Id" + "" + id)
                            // Log.d("friendId", "list position"+""+idsList.size)
                        }
                    }else {
                        Log.d("friendId", "snapshot not exist")

                    }
                }

                override fun onCancelled(error: DatabaseError) {
                    Log.d("friendId", "error"+error.message.toString())

                }

            })


    private fun sendNotifcatiosToFriends( friendId : String) {
        if(friendId != null) {
            val map: HashMap<String, Any> = HashMap()
            map.put("tittle", "notification tittle")
            map.put("body", "notification body")

            val ref = Firebase.database.reference.child("users").child(friendId)
                .child("notifications")
            ref.updateChildren(map)
        }else{
            Log.d("friendId", "friend id is null")

        }

    }

【问题讨论】:

    标签: android firebase kotlin firebase-realtime-database


    【解决方案1】:
    for (i in snapshot.children) {
        //val model = snapshot.getValue(friendsIdsModel::class.java)
        val id = snapshot.child("phone").getValue(String::class.java)
    

    这里的 for 循环是无用的,因为在每次迭代中,您都使用从 Firebase 接收到的相同的 snapshot 对象;尽管您需要通过迭代使用每个单独的子产量(即i var)。

    所以,将snapshot 替换为i

    for (i in snapshot.children) {
        //val model = i.getValue(friendsIdsModel::class.java)
        val id = i.child("phone").getValue(String::class.java)
    

    如果您仍然遇到问题,请提供您的数据库的屏幕截图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-25
      • 2023-03-25
      • 2013-08-25
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多