简体   繁体   中英

Accessing parent and child nodes in Firebase for Android

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?

在此处输入图像描述

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/penny@gm.com/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!
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM