简体   繁体   English

如何从 Firebase 中检索子数据?

[英]How to retrieve the child data from Firebase?

My database looks as follows, in here I want to retrieve the data inside the mylocation child (see the attached image here ).我的数据库如下所示,在这里我想检索mylocation子项中的数据(请参见此处的附图)。 But it is not working.但它不起作用。 How to solve that?如何解决?

My current code looks as this,我当前的代码如下所示,

private void loadAddress() {
        DatabaseReference ref= FirebaseDatabase.getInstance().getReference("Users");
        ref.orderByChild("uid").equalTo(firebaseAuth.getUid())
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        for(DataSnapshot ds: dataSnapshot.getChildren()){
                            String name=""+ds.child("name").getValue();

                            String lat=""+ds.child("name2").getValue();

                             addresstv.setText(name);

                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });



    }

To get the data under mylocation , you use an explicit call to that child, like in the following lines of code:要获取mylocation下的数据,请使用对该子项的显式调用,如以下代码行所示:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String name = dataSnapshot.child("mylocation").child("name2").getValue(String.class);
        double latitude = dataSnapshot.child("mylocation").child("latitude").getValue(Double.class);
        double longitude = dataSnapshot.child("mylocation").child("longitude").getValue(Double.class);
        Log.d("TAG", name + "/" + latitude + "/" + longitude);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
    }
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

The result in the logcat will be: logcat 中的结果将是:

5555/79.8571577/6.9448882

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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