I have to check that if the user who clicked already participates in this event then he is inside the "Partecipanti" field that Toast that I put comes out otherwise it is inserted in the "Partecipanti". How can i do? i put below the code i have made
if(dataSnapshot.exists()) return value null. Not show the Toast, Why?
Database example:https://imgur.com/a/QgeQspW
@Override
public void onInfoWindowClick(@NonNull Marker marker) {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
LatLng latLon = marker.getPosition();
//Cycle through places array
for(Incontro incontro : Incontri) {
if (latLon.equals(incontro.getLatlng())) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Incontro")
.child(incontro.getIncontroidId())
.child("Partecipanti");
Query query = reference.child("").equalTo(uid);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Toast.makeText(Cercaincontro.this, "You are already attending this event", Toast.LENGTH_SHORT).show();
}else{
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Incontro").child(incontro.getIncontroidId());
HashMap<String, Object> hashMap1 = new HashMap<>();
hashMap1.put("userid", firebaseUser.getUid());
reference1.child("Partecipanti").child(uid).setValue(true);
reference1.child("partecipanti").setValue(ServerValue.increment(1));
}
}
@Override
public void onCancelled(DatabaseError databaseError) { throw databaseError.toException();
}
});
}
}
}
CodePudding user response:
When you're using:
Query query = reference.child("").equalTo(uid);
You're checking an empty string against a UID, which obviously returns no results. If you want to check if a particular UID exists under the Partecipanti
node, there is no need to use a query, simply build a reference and check if the child exists:
DatabaseReference uidRef = reference.child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Log.d("TAG", "The UID already exists.");
} else {
Log.d("TAG", "The UID doesn't exist.");
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.d("TAG", error.getMessage()); //Never ignore potential errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);