Firebase检索儿童Android

时间:2015-01-08 19:45:44

标签: android firebase

我在Android上访问Firebase。我想从树中检索一个孩子。我的代码是(更新的)

         f.child("Germany").child("Username").child("Alan Turing").addChildEventListener(new ChildEventListener() {
        // Retrieve new posts as they are added to Firebase
        @Override
        public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
            Map<String, Object> newPost = (Map<String, Object>) snapshot.getValue();
            System.out.println("Author: " + newPost.get("Message"));
            disp_msg = (TextView)findViewById(R.id.display_msg);
            disp_msg.setText(newPost.get("Message").toString());
           // System.out.println("Title: " + newPost.get("title"));
        }

在我的火力架中,我有

Language
  Germany
    Username
      Alan Turing
        Message
          -Jf6ShYy7niHrqg_x4Tc: "tom"
          -Jf9v0xHAxINUUANrORU: "perfect"

当我运行上面的代码时,我得到:

Author: {
  Username={
    Alan Turing={
      Message={
        -Jf6ShYy7niHrqg_x4Tc=tom, 
        -Jf9v0xHAxINUUANrORU=perfect!
      }
    }
  }
}

但我只想要消息,而不是整个Firebase数据库。

那么我该如何获得指定的孩子?

到目前为止只有这个有效,但它会返回整个firebase:

         f.addChildEventListener(new ChildEventListener() {
        // Retrieve new posts as they are added to Firebase
        @Override
        public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
            Map<String, Object> newPost = (Map<String, Object>) snapshot.getValue();
            System.out.println("Author: " + newPost.get("Germany"));
            disp_msg = (TextView)findViewById(R.id.display_msg);
            disp_msg.setText(newPost.get("Germany").toString());
           // System.out.println("Title: " + newPost.get("title"));
        }

我按如下方式存储:

Firebase usersRef = f.child("Language");
usersRef .child("Germany").child("Username").child("Alan Turing").child("Message").push().setValue(writeMsgField.getText().toString());

1 个答案:

答案 0 :(得分:7)

您可以通过在根目录下构建Firebase引用来直接寻址子节点:

f.child("Germany")
 .child("Username")
 .child("Alan Turing")
 .child("Message")
 .addChildEventListener... 

或者更简洁:

f.child("Germany/Username/Alan Turing/Message").addChildEventListener.... 

您真的应该遵循Firebase Android guide,因为how data is structured in Firebase上的主题涵盖了数据结构。花一些时间在该指南上现在将为您节省更多时间(以及许多问题)。