如何从Android中的Firebase获取子节点的子节点?

时间:2018-05-08 01:31:51

标签: android firebase firebase-realtime-database

my database

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

要显示这些值,请使用以下代码:

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);

输出将是:

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

答案 1 :(得分:0)

  1. 声明一个Data baseReference对象(编辑字符串&#34; azone&#34;以匹配您的节点密钥):

    DatabaseReference userSettingRef = 
                    FirebaseDatabase.getInstance().getReference()
                            .child("azone")
                            .child("user_account_settings")
                            .child(getUserId());
    
  2. 添加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());
                    // ...
                }
            });