Search code examples
javaandroidfirebasegoogle-cloud-platformfirebase-realtime-database

How to read data from Firebase Database? - Java


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?

enter image description here

I read the player's name in a different way, which cannot be repeated with victories and defeats.


Solution

  • 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.