How to get the key from the value in firebase

前端 未结 7 2033
挽巷
挽巷 2020-12-01 10:04

How do I get the key \"-KLpcURDV68BcbAvlPFy\" when I know the field \"name\" contains \"efg\" in the following structure in Firebase.

clubs
    -KLpcURDV68Bc         


        
7条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 10:20

    We can use HashMap.

    initialize:

    String for storing Key value. ModelClass for storing you data.

    val hashMap: HashMap = hashMapOf()
    databaseReference.child("/Product").orderByChild("ProductName")
            .addValueEventListener(object : ValueEventListener {
                override fun onCancelled(p0: DatabaseError) {
    
                }
    
                override fun onDataChange(p0: DataSnapshot) {
                    /*p0.children.mapNotNullTo(models) { it.getValue(ProductModel::class.java) }.run {
    
                    }*/
                    p0.children.forEach {
                        val value = it.getValue(ProductModel::class.java) as ProductModel
                        hashMap[it.key!!] = value
                    }.run { adp.update(hashMap) }
                }
            })
    

    after this we can also get key & its value by using (index)

    5 is Index

    hashMap.keys.elementAt(5)
    hashMap.values.elementAt(5)
    

提交回复
热议问题