如何在Andoird中使用Java获取Firebase中子级的列表大小?

时间:2019-10-02 02:34:20

标签: java android firebase firebase-realtime-database

我有一些按钮,如果list size from child "pin" on firebase != 0,按钮标题将更改为“ insert your pin”。

在那里,添加新的实际可用的图钉,但是如何检测size != 0

我的代码:

reference.child("pin").child(userID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    Pin pinLogin = snapshot.getValue(Pin.class);
                    pinLogin.setKey(pinLogin.getKey());

                    pin.add(pinLogin);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

我的按钮逻辑:

          if(pin.size == 0){
                        reference.child("pin").child(userID).push()
                                .setValue(new Pin(pinEditText))
                                .addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        dialog.setTitleText("Success");
                                        dialog.setContentText("Pin Has Been Added!");
                                        dialog.show();
                                    }
                                })
                                .addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        dialogError.setTitleText("Error");
                                        dialogError.setContentText(e.getMessage());
                                    }
                                });
                  }else{
                     button.setText("Insert Your Pin");

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

要获取尺寸,请使用dataSnapshot.getChildrenCount()

reference.child("pin").child(userID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                long size= dataSnapshot.getChildrenCount();

                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    // rest of code