Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How know if a Firebase list is void?

I use the ChildEventListener following the doc. During the data loading, I just make visible a progress drawable in a listview

  • If the list is not empty, then I hide/null the progress view.
  • If the list is void, I display "no item"

    // Get a reference to our posts
    Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");
    
    ref.addChildEventListener(new ChildEventListener() {
        // Retrieve new posts as they are added to the database
        @Override
        public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
            BlogPost newPost = snapshot.getValue(BlogPost.class);
            System.out.println("Author: " + newPost.getAuthor());
            System.out.println("Title: " + newPost.getTitle());
        }
    
        //... ChildEventListener also defines onChildChanged, onChildRemoved,
        //    onChildMoved and onCanceled, covered in later sections.
    });
    

With ref.addValueEventListenerwe can just check that the datasnapshotis null to know it.

How do know that the list is void ? Is it possible ? Without first checking with addValueEventListener ?

like image 862
Anthony Avatar asked Jan 25 '26 00:01

Anthony


1 Answers

You can only know that there are no items in the list by attaching a ValueEventListener.

ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        if (!snapshot.hasChildren()) {
            System.out.println("List is empty");
        }
    }
    @Override
    public void onCancelled(FirebaseError error) {
    }
}

But keep in mind that usually if you call addChildEventListener(), you'll end up storing the items in some internal storage such as a List. You can also simply check if that internal storage is empty (after onChildRemoved() is triggered) and print the message there.

like image 127
Frank van Puffelen Avatar answered Jan 27 '26 13:01

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!