Mohamed Fayez
Mohamed Fayez

Reputation: 13

Firebase getting String Value Always Return Null

I trying to get a user's friends' keys or ids, then send notifications to all of them, but when I value their

this is my code

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

        }

    }

Upvotes: 1

Views: 299

Answers (1)

Zain
Zain

Reputation: 40810

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

Here the for loop is useless, because on every iteration you use the same snapshot object which is received from Firebase; although you need to use each individual child yield by an iteration (which is the i var).

So, replace snapshot with i:

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

If still you face issues, please provide a screenshot of your database.

Upvotes: 1

Related Questions