Chouaieb
Chouaieb

Reputation: 11

How to Get children of child nodes from Firebase in android?

my database :

class UserAccountSettings {
    private String user_id;
    private String name ;
    private float rate;
    private String profile_photo;
    private ArrayList<Activity> activities ;
} 

thanks for your help!

Upvotes: 0

Views: 3438

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

To display those values, please use the following code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference activitiesRef = rootRef.child("user_account_settings").child(uid).child("activities");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String user_id = dataSnapshot.child("user_id").getValue(String.class);
        String name = dataSnapshot.child("name").getValue(String.class);
        float rate = dataSnapshot.child("rate").getValue(Float.class);
        String profile_photo = dataSnapshot.child("profile_photo").getValue(String.class);
        Log.d("TAG", user_id + " / " +
            profile_photo + " / " +
            rate + " / " +
            profile_photo);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
activitiesRef.addListenerForSingleValueEvent(valueEventListener);

The output will be:

mVeg... / Debbebi / 0 / http://...

Upvotes: 1

Fazan Cheng
Fazan Cheng

Reputation: 916

  1. declare a Data baseReference object (edit the string "azone" to match with your node key):

    DatabaseReference userSettingRef = 
                    FirebaseDatabase.getInstance().getReference()
                            .child("azone")
                            .child("user_account_settings")
                            .child(getUserId());
    
  2. add a ValueEventListener:

    userSettingRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        // Get Post object and use the values to update the UI
                        UserAccountSettings setting = dataSnapshot.getValue(UserAccountSettings .class);
                    if (setting!= null) {
                       // do something here
    
                    }
    
                }
    
                @Override
                public void onCancelled(DatabaseError databaseError) {
                    // Getting Post failed, log a recipientMessage
                    Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
                    // ...
                }
            });
    

Upvotes: 0

Related Questions