Get child ID from Firebase android [closed]

2020-05-08 07:24发布

问题:

I'm quite new to android development and I'm developing an android app with Firebase to get a person's name and adress. My database looks like this:

    Users
       id: user1
       id: user2
       id: user3

    Adresses
       id: adress1
       id: adress2
       id: adress3

I want to get 'id' from a user to get the corresponding adress, but I cannot seem to achieve it. Any ideas?

回答1:

Fetch all the userids like this :-

List<String> userIdList = new ArrayList();
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference();
databaseRef.child("User").addValueEventListener(new ValueEventListener() {
    @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
           if(dataSnapshot==null)return;
          for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) { 
               userIdList.add(postSnapShot.getKey());
          }
   }

@Override
public void onCancelled(DatabaseError   databaseError) {
    // Error
  }
};

Get the address corresponding to any userId

databaseRef.child("Adresses").orderByKey().equalTo(userIdList.get(0)).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot==null || dataSnapshot.getChildren()==null || !dataSnapshot.getChildren().iterator().hasNext()){
   String address = dataSnapshot.getValue(String.class);
 }
}

@Override
 public void onCancelled(DatabaseError databaseError) {
 // Error
 }
};