Home > Enterprise >  Accessing parent and child nodes in Firebase for Android
Accessing parent and child nodes in Firebase for Android

Time:08-07

I want to access these child node data from the Firebase Realtime Database and display them in my app in Android Studio. How do I write code for that?

enter image description here

CodePudding user response:

It's best to add to your question what Frank asked for, but since you're new, I'll give it a try and write some code for you. So in order to read the value of Age, Email, and Gender, you have to create a reference and attach a listener to it. Assuming that F1EQ...v302 is the UID of the logged-in user, the code for reading the data should look like this:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = db.child("All Users").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            String age = snapshot.child("Age").getValue(String.class);
            String email = snapshot.child("Email").getValue(String.class);
            String gender = snapshot.child("Gender").getValue(String.class);
            Log.d("TAG", age   "/"   email   "/"   gender);
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

The result in the logcat will be:

18/[email protected]/Female

Besides that, it makes more sense to set the Age property to be a number, rather than a string. If you need it later as a string, you can simply convert it into your application code.

Edit:

If you want to get the data from all users, indeed you need a loop:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference allUsersRef = db.child("All Users");
allUsersRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot ds : task.getResult().getChildren()) {
                String age = ds.child("Age").getValue(String.class);
                String email = ds.child("Email").getValue(String.class);
                String gender = ds.child("Gender").getValue(String.class);
                Log.d("TAG", age   "/"   email   "/"   gender);
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});
  • Related