Firebase/Android如何获取子项键和值? [英] Firebase/android how get children keys and values?

查看:73
本文介绍了Firebase/Android如何获取子项键和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据库:

users: {
     0 : {
         name: xx
         age: 11
         books:{
               0 : true
               3 : true
         }
     }
     1 : {
         name: yy
         age: 12
         books:{
               1 : true
               4 : true
         }
     }
}

我参考了数据库管理员:

I have ref to db als:

database = FirebaseDatabase.getInstance();
refdb = database.getReference();

和查询伙伴:

Query = refdb.child("users");

我需要获取所有对(name:value),并且需要为用户获取书籍对(id:true)als:

i need to get all pairs (name:value) and for users pairs of books (id:true) als:

0 : true
3 : true

我正在使用它来获取配对(id:true):

I'm using this to get pairs (id:true):

refdb.child("users").child("books").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) { 
        pck.setText(pack);
        for (DataSnapshot dttSnapshot2 : dataSnapshot.getChildren()) {
             pack = dttSnapshot2 .getKey().toString()+":"+dttSnapshot2 .getValue().toString();
             pck.append(pack);
         }
...

其中pck是textView. 我的问题是每次他在textView中打印空字符串时. 如何获取这些数据并将其写入textview?

Where pck is a textView. My problem is that everytime he print the empty string in textView. How can I get those data and write them in a textview?

推荐答案

refdb.child("users").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for(DataSnapshot uniqueKeySnapshot : dataSnapshot.getChildren()){
            //Loop 1 to go through all the child nodes of users
            for(DataSnapshot booksSnapshot : uniqueKey.child("Books").getChildren()){
            //loop 2 to go through all the child nodes of books node
                String bookskey = booksSnapshot.getKey();
                String booksValue = booksSnapshot.getValue();
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
}

到目前为止,我尚未测试此代码,但希望您能理解.无法跳过唯一ID节点,因为Firebase不知道您要从中提取数据的唯一ID.因此,要么通过使用foreach循环遍历所有唯一ID,要么指定要从中获取数据的唯一ID.

I haven't tested this code as of now, but I hope you get the idea. The unique ID nodes cannot be skipped because firebase does not know which unique id you want to extract data from. So either go through all the unique IDs by using a foreach loop or specify the unique ID from which you want the data.

这篇关于Firebase/Android如何获取子项键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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