从Firebase获取特定的孩子

时间:2017-01-08 14:02:27

标签: android firebase firebase-realtime-database

在我的Firebase中,我有一个应用程序数据库。让我们说这是我的Firebase JSON:

{
  "Users" :{
    "User1":{
      "City": "Genk"
    }
    ,"User2":{
      "City": "Hasselt"
    }
    ,"User3":{
      "City": "Genk"
    }
    ,"User4":{
      "City": "As"
    }
    ,"User5":{
      "City": "Genk"
    }
  }
}

现在我想要的是一个包含城市Genk的所有用户的ArrayList。这怎么可能?我想使用此ArrayList将位于城市Genk中的特定用户放入ListView中。

2 个答案:

答案 0 :(得分:0)

我建议您从根目录创建另一个子项,例如" UsersCity",这样您就可以调用此子项并将其检索到列表视图。这就是我的所作所为:

String key = mDatabase.child("post").push().getKey();
UserPost userPost = new UserPost(author,uid,setemoticon,postData,mDate,latlng);
Map<String, Object> postValues = userPost.toMap();

Map<String, Object> childUpdates = new HashMap<>();
                childUpdates.put("/post/" + key,postValues);
                childUpdates.put("/user-post/" + uid + "/" + key, postValues);

mDatabase.updateChildren(childUpdates);

这是Json的输出:

{
"post" : {
"-KcGVPpS9CTWPNax61wf" : {
  "authorName" : "Test 1",
  "dateCreated" : {
    "dateCreated" : 1486352395887
  },
  "postDescription" : "sample post",
  "postEmotion" : 2130837658,
  "userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1"
}
},
"user-post" : {
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : {
  "-KcGVPpS9CTWPNax61wf" : {
    "authorName" : "Test 1",
    "dateCreated" : {
      "dateCreated" : 1486352395887
    },
    "postDescription" : "sample post",
    "postEmotion" : 2130837658,
    "userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1"
  }
}
},
//This child node is for users where you'll want to get the $uid to use for  creation of other child nodes.
"users" : {
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : {
  "fullname" : "Test 1"
  }
 }
}

我只是一个新手程序员,我知道我的答案不是最好的,但我希望它可以帮助你解决问题。 :)

答案 1 :(得分:0)

只需获取特定节点数据,并且它非常适合我

mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {


        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Log.e(TAG, "======="+postSnapshot.child("email").getValue());
            Log.e(TAG, "======="+postSnapshot.child("name").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.e(TAG, "Failed to read app title value.", error.toException());
    }
});
相关问题