繁体   English   中英

如何在 firebase 中实时检索此元素?

[英]How can I retrieve this element in firebase realtime?

我将项目保存到 firebase 并得到以下结构

在此处输入图像描述

我正在使用以下代码尝试检索第二个孩子内部的描述精确数据

 DatabaseReference itemFactura = FirebaseDatabase.getInstance().getReference().child("factura");
 itemFactura.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        if(dataSnapshot.exists()){
            int cantidad = 0;

            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                if(Boolean.parseBoolean(snapshot.child("estado").getValue().toString())){
                            ArrayList<String> elementos = new ArrayList<String>();
                            elementos.add(snapshot.child("descripcion").getValue().toString());
                            elementos.add(snapshot.child("precio").getValue().toString());
                            tabla.agregarFilaTabla(elementos);
                            cantidad = Integer.parseInt(snapshot.child("precio").getValue().toString()) + cantidad;
                }
            }
            cantidadTotal.setText(String.valueOf(cantidad));
        }

    }

但它把我标记为 null 因为它找不到它们

您在 JSON 中有两个带有动态键的嵌套级别,因此您需要在onDataChange中的getChildren()上进行两个嵌套循环:

DatabaseReference itemFactura = FirebaseDatabase.getInstance().getReference().child("factura");
 itemFactura.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists()){
            int cantidad = 0;
            for (DataSnapshot level1snapshot : dataSnapshot.getChildren()){
                for (DataSnapshot level2snapshot : level1snapshot.getChildren()){
                    if(level2snapshot.child("estado").getValue(Boolean.class) != null){
                        ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM