如何在Java中从Firebase获取Childs的价值 [英] How to get value of Child of childs from firebase in java

查看:27
本文介绍了如何在Java中从Firebase获取Childs的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从中获取 mailID 中的email值和mailText中的主题和标题.我能够访问单个孩子的值,但是当尝试显示所有内容时显示空值时三.

From this I want take the value of email from mailID and subject, title from mailText.i'm able to access the value of single child but when it show null with when try get with all three.

以下代码适用于独生子女:

Following code working for single child:

DatabaseReference databaseRef = database.getReference("/");
    databaseRef.addValueEventListener(new ValueEventListener() {
                 public void onDataChange(DataSnapshot dataSnapshot) {
                    ArrayList<String> email = new ArrayList();
                     for (DataSnapshot sd: dataSnapshot.getChildren()) {
                         String emailStr = sd.child("email").getValue(String.class);
                         email.add(emailStr);
                         System.out.println(email);
                         }
                     latch.countDown();
                     }

上面的代码为我提供了包含所有电子邮件的数组,就像我想获取电子邮件,标题和主题的值一样.

Above code gives me array contain the all email like that i want to take value of email,title and subject.

推荐答案

假设 new 节点是Firebase根目录的直接子级,要实现您在注释中解释的内容,请使用以下代码行:

Assuming that the new node is a direct child of your Firebase root, to achieve what you have explained in your comments, please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference newRef = rootRef.child("new");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.child("mailID").getChildren()) {
            String email = ds.child("email").getValue(String.class);
            String name = ds.child("name").getValue(String.class);
            Log.d("TAG", email + " / " + name);
        }
        for(DataSnapshot ds : dataSnapshot.child("mailText").getChildren()) {
            String title = ds.child("title").getValue(String.class);
            String subject = ds.child("subject").getValue(String.class);
            Log.d("TAG", title + " / " + subject);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
newRef.addListenerForSingleValueEvent(valueEventListener);

如您所见,您需要在树层次结构中将侦听器附加一级,并使用 getChildren()方法两次遍历子级.

As you see, you need to attach a listener one step higher in your tree hierarchy and to loop throught the children using getChildren() method twice.

这篇关于如何在Java中从Firebase获取Childs的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆