I'm making a game, if the player wins, then the victory is added to the database. How can I read the data from here?
and paste here:
I read the player's name in a different way, which cannot be repeated with victories and defeats.
CodePudding user response:
To be able to read the data under the jjjj
node, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = db.child("players").child("jjjj");
nameRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
String loses = snapshot.child("loses").getValue(Long.class);
String name = snapshot.child("name").getValue(String.class);
String wins = snapshot.child("wins").getValue(Long.class);
Log.d("TAG", loses "/" name "/" wins);
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
3/jjjj/4
Things to notice:
- Always create a reference that points to the node that you want to read.
- If your database is located in another lcoation than the default, check this answer out.
CodePudding user response:
use this method
This is the method of fetching data from the firebase realtime database
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("players").child(name).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});