Skip to content Skip to sidebar Skip to footer

Display Target Data From Firebase

I display a list of my targets in fragmentA, when I click on one of them, I pass the guid of this target to the fragmentB After that, I try in the fragmentB display the data of thi

Solution 1:

To display the data that belongs to a single guid, you should use a query and then iterate through the DataSnapshot object like in the following lines of code:

val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseDatabase.getInstance().reference
val targetsRef = rootRef!!.child("targets").child("users").child(uid).child("targets")
val query = targetsRef.orderByChild("guid").equalTo("-LmfEVnwgqCUqt7beHDg")
val valueEventListener = object : ValueEventListener {
    overridefunonDataChange(dataSnapshot: DataSnapshot) {
        for (ds in dataSnapshot.children) {
            val target = ds.getValue(Target::class.java)
            Log.d(TAG, target.name)
        }
    }

    overridefunonCancelled(databaseError: DatabaseError) {
        Log.d(TAG, databaseError.getMessage()) //Don't ignore errors!
    }
}
query.addListenerForSingleValueEvent(valueEventListener)

The result in the logcat will be:

fgg

Solution 2:

You are not getting any data because to get above data your guid value in query should be "-LmfEVnx-y7c3oh8_U9F" but you are passing "-LmfEVnwgqCUqt7beHDg".

You can try below query to get above data:

val uid = firebaseUser!!.uid
        // Attach a listener to read the data at the target id
        databaseReference?.child("targets")?.child("users")?.child(uid)?.child("targets")?.orderByChild("guid").equalTo(guid)?.addValueEventListener(object : ValueEventListener {
            overridefunonDataChange(dataSnapshot: DataSnapshot) {
                valdata = dataSnapshot.value as? HashMap<String, String>?
                val name = data?.get("name") ?: ""val description = data?.get("description") ?: ""if (name.isEmpty()) Log.d("some", "nameIsEmpty")
                else updateViewsContent(name = name, description = description)
            }

            overridefunonCancelled(databaseError: DatabaseError) {
                Log.d("some", databaseError.message)
            }
        })

Post a Comment for "Display Target Data From Firebase"