我在Android上访问Firebase.我想从树中检索一个孩子.我的代码是(更新的) f.child("Germany").child("Username").child("Alan Turing").addChildEventListener(new ChildEventListener() { // Retrieve new posts as they are added t
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());您可以通过在根目录下构建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的主题中得到了很好的介绍.花一些时间在这个指南上现在可以节省你很多时间(以及许多问题).